【发布时间】:2017-10-05 20:54:16
【问题描述】:
我需要解析一个csv 文件。
输入:文件+名称
Index | writer | year | words
0 | Philip | 1994 | this is first row
1 | Heinz | 2000 | python is wonderful (new line) second line
2 | Thomas | 1993 | i don't like this
3 | Heinz | 1898 | this is another row
. | . | . | .
. | . | . | .
N | Fritz | 2014 | i hate man united
输出:名称对应的所有单词列表
l = ['python is wonderful second line', 'this is another row']
我尝试了什么?
import csv
import sys
class artist:
def __init__(self, name, file):
self.file = file
self.name = name
self.list = []
def extractText(self):
with open(self.file, 'rb') as f:
reader = csv.reader(f)
temp = list(reader)
k = len(temp)
for i in range(1, k):
s = temp[i]
if s[1] == self.name:
self.list.append(str(s[3]))
if __name__ == '__main__':
# arguements
inputFile = str(sys.argv[1])
Heinz = artist('Heinz', inputFile)
Heinz.extractText()
print(Heinz.list)
输出为:
["python is wonderful\r\nsecond line", 'this is another row']
对于包含多于一行单词的单元格,我如何摆脱\r\n,并且循环非常慢,是否可以改进?
【问题讨论】:
标签: python csv parsing python-3.5