我正在覆盖csv.Dictreader.fieldnames
属性,如下所示,从csv文件中读取所有标题,不带空格和小写。
import csv
class MyDictReader(csv.DictReader):
@property
def fieldnames(self):
return [field.strip().lower() for field in super(MyDictReader, self).fieldnames]
现在我的问题是,如何通过自动strip()
和lower()
查询来访问字段名?
这是我如何手动完成的:
csvDict = MyDictReader(open('csv-file.csv', 'rU'))
for lineDict in csvDict:
query = ' Column_A'.strip().lower()
print(lineDict[query])
有什么想法吗?
答案 0 :(得分:2)
根据Pedro Romano的建议,我编写了以下示例。
import csv
class DictReaderInsensitive(csv.DictReader):
# This class overrides the csv.fieldnames property.
# All fieldnames are without white space and in lower case
@property
def fieldnames(self):
return [field.strip().lower() for field in super(DictReaderInsensitive, self).fieldnames]
def __next__(self):
# get the result from the original __next__, but store it in DictInsensitive
dInsensitive = DictInsensitive()
dOriginal = super(DictReaderInsensitive, self).__next__()
# store all pairs from the old dict in the new, custom one
for key, value in dOriginal.items():
dInsensitive[key] = value
return dInsensitive
class DictInsensitive(dict):
# This class overrides the __getitem__ method to automatically strip() and lower() the input key
def __getitem__(self, key):
return dict.__getitem__(self, key.strip().lower())
对于包含
标题的文件您可以访问以下列:
csvDict = DictReaderInsensitive(open('csv-file.csv', 'rU'))
for lineDict in csvDict:
print(lineDict[' Column_A']) # or
print(lineDict['Column_A']) # or
print(lineDict[' column_a']) # all returns the same
答案 1 :(得分:1)
你必须分两步完成:
dict
方法创建__getitem__
专精,将.strip().lower()
应用于其key
参数。__next__
专门课程上的MyDictReader
,以返回使用csv.DictReader
超类__next__
方法返回的词典初始化的一个特殊词典。