[英]How can i add previous results from a loop into a dictionary?
我正在尝试将循环的先前结果添加到字典中。 我希望它在迭代后添加新结果。 我的意思是字典保存了每次迭代的结果。 所以它从一个结果开始,然后添加迭代的下一个结果,但不在同一个字典中。
一个例子,这是在第一次循环之后。
{'head': 1, 'leg':1, 'arm':2}
然后在下一个循环中,它会看到该行
{'eye': 1, 'leg':1, 'arm':2}
它创造了
{'head': 1, 'leg':1, 'arm':2}
{'eye': 1, 'leg':1, 'arm':2}
我目前有以下代码:
import nltk
import numpy
from nltk.corpus import stopwords
stopwoorden = set(stopwords.words('english'))
with open("test1.txt") as t1, open("test2.txt") as t2:
test1 = t1.read()
test2 = t2.read()
for test in [test1,test2]:
words = test.split()
words = [word.lower()for word in words]
stopwoorden_removed = [word for word in words if word not in stopwoorden]
tf = {}
for word in stopwoorden_removed:
if word in tf:
tf[word] = tf[word] + 1
elif word not in tf:
tf[word] = 1
print(tf)
我知道 append 不适用于字典。 我不知道如何在此实现.update function。
任何帮助表示赞赏。
在 for 循环之前声明 tf = {}。 其他一切看起来都很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.