gpt4 book ai didi

带有空格或特殊字符的 Python 类型定义

转载 作者:太空宇宙 更新时间:2023-11-03 19:57:35 27 4
gpt4 key购买 nike

我有一个 python 3.8 例程,旨在向带有标题的 CSV 文件添加键入内容,如下所示:

class Record(NamedTuple):
""" Define the fields and their types in a record. """
Category : str
Item : str
Serving Size : str
Calories : int
SaturatedFat(%pctDaily) : int
Sugars : int
Protein : int

@classmethod
def _transform(cls: 'Record', dct: dict) -> dict:
""" Convert string values in given dictionary to corresponding Record
field type.
"""
return {field: cls._field_types[field](value)
for field, value in dct.items()}

我发现任何包含空格或特殊字符的 header 字段都会出错,例如

Saturated(%Fat) : float
^
SyntaxError: invalid syntax

有什么想法可以解决这个问题吗?TIA,亚历克斯

最佳答案

您正在尝试使用非法字段名称创建 NamedTuple。引用自documentation for NamedTuple :

Any valid Python identifier may be used for a fieldname except for names starting with an underscore. Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be a keyword such as class, for, return, global, pass, or raise.

您需要 NamedTuple 的所有装饰吗?从我看来,拥有一个自定义的类似字典会很适合你:

class Record:
def __init__(self, record):
self._fields = {}
for k, t in {
"Category": str,
"Saturated(%Fat)": float
}.items():
self._fields[k] = t(record[k])

def __getitem__(self, key):
return self._fields[key]

注意构造函数如何知道哪些字段必须存在。像这样使用它:

record = Record({"Category": "foo", "Saturated(%Fat)": "5.5"})
record["Saturated(%Fat)"] # 5.5

这是一个准系统解决方案,您可能需要添加其他方法,例如 __len__()items()。查看Emulating Container Types供您选择。

关于带有空格或特殊字符的 Python 类型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59459697/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com