python - 使用 Python 以小写形式读取 CSV 文件

标签 python csv python-3.x map-function

我正在将 CSV 文件读入命名元组,如下所示:

import csv
from collections import namedtuple

#So we can handle bad CSV files gracefully
def unfussy_reader(reader):
    while True:
        try:
            yield next(reader.lower())

        # This is a bad row that has an error in it (csv.Error)
        # Alternately it may be a line that doesn't map to the structure we've been given (TypeError)
        except (csv.Error, TypeError):
            pass

        continue

# Create the CSV reader object
csv_reader = csv.reader(file_stream, delimiter=' ', quotechar='"', escapechar='^')

# Set up the named tuple
csvline = namedtuple('csv_line', 'field1, field2, field3')

# Create the named tuple mapping object
map_to_tuple = map(csvline._make, csv_reader)

for line in unfussy_reader(map_to_tuple):
    # do stuff

这很好用,但我的问题是 - 我希望 CSV 的所有内容都以小写形式读取。根据this question ,一个简单的 lambda 就可以做到这一点: map(lambda x:x.lower(),["A","B","C"]) 但在数据最终进入元组之前我找不到任何地方可以放置它(因此无法更改)。

有没有办法在这个结构(Python 3.5)中做到这一点?

最佳答案

您可以在为其创建 CSV 读取器之前将 lower 转换应用于流。

lower_stream = (line.lower() for line in file_stream)
csv_reader = csv.reader(lower_stream, delimiter=' ', quotechar='"', escapechar='^')

lower_stream 赋值目标周围的括号指定 generator expression 。它不会用完 file_stream,也不会将所有 file_stream 拉入内存。

关于python - 使用 Python 以小写形式读取 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34578820/

相关文章:

python - 导入错误 : No module named _mysql

Python 2 CSV 编写器在 Windows 上产生错误的行终止符

python - __init__() 得到了一个意外的关键字参数 'text'

python - 查找数据框中每列的最高 n 值

java - 通过java将csv转换为.xls,其中分隔分隔未正确完成

python-3.x - 如何在文本分类的拆分数据测试和训练中修复 'typeerror: only integer scalar arrays can be converted to a scalar index'

Python pptx (Power Point) 查找和替换文本 (ctrl + H)

python 中的curl --interface 等价物

python - Tkinter 字体大小仅影响 Raspberry pi 上字母之间的间隙

python - 为什么 numpy/pandas 解析长行的 csv 文件这么慢?