[英]Python csv.reader is printing the last line a second time
I have a 2 column comma separated text file of English sentences and their translation into another language with each translation pair on a new row eg 我有两列逗号分隔的英文句子文本文件,并将其翻译成另一种语言,每个翻译对都在新行上,例如
i like cats,me gustan los gatos
hello,hola
I wanted to open that file and just get the second part of the pair (the translation) and have a list of those translations. 我想打开该文件,然后获取该对的第二部分(翻译),并列出这些翻译。 I have used the code shown.
我已经使用了显示的代码。 However, the output is that the last item is always printed again at the end after the list, which I don't want.
但是,输出结果是总是在列表之后的末尾再次打印最后一个项目,这是我不希望的。
with open('translate_outputs.txt', newline ='') as translations:
translation_reader = csv.reader(translations, delimiter = ',')
for translation in translation_reader:
just_translation = translation[1].lower()
translation_list = []
translation_list.append(just_translation)
print(translation_list)
Expected result: 预期结果:
['me gustan los gatos']
['hola']
Actual result: 实际结果:
['me gustan los gatos']
['hola']
hola
A shorted version of the code that give the expected output. 提供预期输出的代码的缩写形式。
(I removed the appending to list) (我删除了追加到列表)
import csv
with open('translate_outputs.txt', newline='') as translations:
translation_reader = csv.reader(translations, delimiter=',')
for translation in translation_reader:
print(translation[1].lower())
output 产量
me gustan los gatos
hola
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.