Read in a CSV file in lower case with Python
我正在将一个csv文件读取到一个名为duple的文件中,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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的所有内容。根据这个问题,一个简单的lambda可以做到:
在这个结构(python 3.5)中有没有一种方法可以做到这一点?
在为流创建csv阅读器之前,可以将
1 2 | lower_stream = (line.lower() for line in file_stream) csv_reader = csv.reader(lower_stream, delimiter=' ', quotechar='"', escapechar='^') |
这个怎么样?
1 | csv_reader = csv.reader(map(lambda line:line.lower(),file_stream), delimiter=' ', quotechar='"', escapechar='^') |