[英]Unexpected output while reading a csv file in a for loop
import csv
if __name__ == "__main__":
words = ["great" , "thanks"]
with open("data/sentiwordnet.tsv", "r") as f:
reader = csv.DictReader(f,delimiter='\t')
for word in xrange(len(words)):
for row in reader:
if row['word_en'] == words[word]:
print float(row["positive"])
print float(row["negative"])
print row["synset"]
結果:
0.75
0.0
124567
上面的結果僅適用於第一個單詞,即“偉大”。 循環到此結束-不會繼續到下一個單詞。
一旦您遍歷了reader
的行,就不會神奇地重新啟動。 交換for
循環,以便您僅通過reader
迭代一次:
for row in reader:
for word in xrange(len(words)):
我只是通過檢查每個單詞是否在您感興趣的一組單詞中來避免重復兩次。它將運行得更快:
import csv
if __name__ == "__main__":
words = {"great" , "thanks"} # sets are faster than lists for checking containment
with open("data/sentiwordnet.tsv", "r") as f:
reader = csv.DictReader(f, delimiter='\t')
for row in reader:
if row['word_en'] in words:
print float(row["positive"])
print float(row["negative"])
print row["synset"]
您可能還需要考慮使用像pandas這樣的程序包來處理表格,這通常會使您的生活更輕松。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.