2016-01-03 195 views
2

我读一个CSV文件转换成namedtuple像这样:阅读CSV文件小写与Python

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)中有没有办法做到这一点?

+1

在'csv_reader = ...'之前添加一行:'file_stream =(line.lower()for file in file_stream)'? – bbayles

+0

@bbayles - 工作,虽然我不得不将它分配给某些东西,然后改变'csv_reader ='行来指向,而不是'file_stream'。发布它作为答案,我会接受。谢谢 –

回答

2

你可以申请你为它创建一个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存入内存。

0

如何:

csv_reader = csv.reader(map(lambda line:line.lower(),file_stream), delimiter=' ', quotechar='"', escapechar='^')