gpt4 book ai didi

python - 是否可以让 csv.DictReader 将某些列格式化为字符串以外的格式?

转载 作者:行者123 更新时间:2023-12-01 05:36:22 25 4
gpt4 key购买 nike

csv.DictReader() 默认情况下将列中的值作为字符串提取。 有没有办法指定某些列的转换?

每次访问由 csv.DictReader() 创建的包含非字符串元素的字典列表时,我最终都会做很多这样的小烦恼:

with open("data.csv","r") as data_file:
items = csv.DictReader(data_file, fieldnames=('id', 'length', 'note'))
for item in items:
item['length'] = float(item['length']) #### <--- MINOR ANNOYANCE
# ... do loop stuff

如果我可以告诉 csv.DictReader 当它到达某个字段时,它应该执行 float() (或 int ()date() 等)转换。

最佳答案

不是开箱即用的,不是。您可以子类化 DictReader() 或创建一个生成器函数来为您映射行:

def convert_fields(iterable, **conversions):
for item in iterable:
for key in item.viewkeys() & conversions:
item[key] = conversions[key](item[key])
yield item

对于 Python 3,请用 dict.viewkeys() 替换 dict.keys(),因为 Python 3 默认返回字典 View 。

用它包装您的 csv.DictReader() ,为每列添加转换函数:

with open("data.csv","r") as data_file:
items = csv.DictReader(data_file, fieldnames=('id', 'length', 'note'))
items = convert_fields(items, length=float)
for item in items:
# item['length'] is now always a float

对于未映射到 python 标识符(带空格等)的列名,请使用 **{..} 语法传入字典:

with open("data.csv","r") as data_file:
items = csv.DictReader(data_file, fieldnames=('id', 'length', 'note'))
fieldconv = {'id': int, 'length': float, 'spaced column': float}
items = convert_fields(items, **fieldconv)
for item in items:
# item['length'] and item['spaced column'] are now floats
# item['id'] is always an int

关于python - 是否可以让 csv.DictReader 将某些列格式化为字符串以外的格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18945534/

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