简体   繁体   English

如何将循环中的先前结果添加到字典中?

[英]How can i add previous results from a loop into a dictionary?

I'm trying to add the previous results of a loop into the dictionary.我正在尝试将循环的先前结果添加到字典中。 I want it to add new results after an iteration.我希望它在迭代后添加新结果。 What I mean by this is a dictionary saves the results from every iteration.我的意思是字典保存了每次迭代的结果。 So it starts with one result and adds the next result of the iteration after that but not in the same dictionary.所以它从一个结果开始,然后添加迭代的下一个结果,但不在同一个字典中。

An example, this is after the first looping over it.一个例子,这是在第一次循环之后。

{'head': 1, 'leg':1, 'arm':2}

Then in the next loop it sees the line然后在下一个循环中,它会看到该行

{'eye': 1, 'leg':1, 'arm':2}

and it creates它创造了

{'head': 1, 'leg':1, 'arm':2}
{'eye': 1, 'leg':1, 'arm':2}

I currently have the following code:我目前有以下代码:

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)

I know append does not work with dictionaries.我知道 append 不适用于字典。 I wouldnt know how to implement the.update function in this.我不知道如何在此实现.update function。

Any help is appreciated.任何帮助表示赞赏。

Declare tf = {} before the for loop.在 for 循环之前声明 tf = {}。 Everything else looks fine.其他一切看起来都很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM