访问csv标头空白区域并且不区分大小写

时间:2012-10-18 14:26:09

标签: python csv python-3.x

我正在覆盖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])

有什么想法吗?

2 个答案:

答案 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())

对于包含

标题的文件
  • “column_A”
  • “column_A”
  • “Column_A”
  • “Column_A”
  • ...

您可以访问以下列:

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)

你必须分两步完成:

  1. 使用dict方法创建__getitem__专精,将.strip().lower()应用于其key参数。
  2. 覆盖__next__专门课程上的MyDictReader,以返回使用csv.DictReader超类__next__方法返回的词典初始化的一个特殊词典。