简体   繁体   中英

Python for loop returns zero after first iteration

I'm trying to write a program that compares each item in a list against the text of a document. The program should then return a new list with a value appended to each item of how many times it matched up against a word in the document. I have a function written that actually does the matching and it works fine on its own. The loop that does the counting also works for single entries. However, when I try to run it for all the entries of the list, it comes back with the proper number for the first list entry and then just gives zeroes back for the rest.

Here's an idea of what it looks like:

    doc = open("C:/...")
    list = ['string_1', 'string_2', 'string_3', ...]
    answer = []
    ...
    [some code]
    ...
    for t in list:
        counter = 0
        for word in doc:
            if func(word,t) == True:
                counter += 1
        answer.append([counter,t])
    print answer

The closest thing to answering my question was this article. However, I do want to reset the counter for each list item and I haven't included the "counter = 0" in the actual "for" statement where the calculation is done.

I have a feeling that it may have to do with the placement of the "counter = 0" assignment, but if I place it outside the "for t in list:" loop, then it just returns the same value for every list entry.

Change your first line to this:

doc = open("C:/...").read().split()

This should return you a list of all the words in the file.

The reason it's failing is because when you do for word in doc: it's iterating through the file. So it can only ever be read once. If you save the contents of the file to a variable you can iterate over it as many times as you like.

This loop is reading to the end of the file

for word in doc:
    ...

You'd need to reopen it or seek back to the beginning.

For a quick hack (i guess your program is a quick hack since you are not bothering to close the file), you could use

doc = list(open("C:/..."))

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