简体   繁体   中英

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. I wouldnt know how to implement the.update function in this.

Any help is appreciated.

Declare tf = {} before the for loop. Everything else looks fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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