[英]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.