我导入CSV文件并循环运行以获得结果。 我想从循环中收集结果,但我只得到最后一行。
例如
test.csv包含
sentence1
sentence2
sentence3
with codecs.open('test.csv', 'r','utf-8') as f:
for line in f:
test = f.readlines()
for t in test:
text = strip_all_entities(strip_links(t)) #cleaning sentence
result = (text+" : "+ "test")
我想要: -
sentence1 : test
sentence2 : test
sentence3 : test
但它只显示了最后一句: -
sentence3 : test
如何修复此代码?
答案 0 :(得分:1)
你应该做一些不同的事情。
首先,readlines()
返回一个字符串数组,其长度等于文件中的行数。这意味着您实际上不必遍历所有行并为每个行调用readlines()
。相反,只需调用一次:
with codecs.open('test.csv', 'r','utf-8') as f:
lines = f.readlines()
其次,如果您只是执行result = something
,结果中的所有先前条目都会被覆盖,这就是您只看到一行的原因。请尝试以下方法:
results = []
for line in lines:
results.append(strip_all_entities(strip_links(lines)) + " : " + "Test")
有关python readlines的更详细介绍,请参阅this link。