I have below Python script, counts the number of words in a text file:
from collections import Counter
def main():
with open(TEXT_FILE) as f:
wordscounts = Counter(f.read().split())
print(wordscounts)
Above gives me:
Counter({'invoice': 10, 'USD': 8, 'order': 5})
Now I want to add these words to another text file dictionary.txt, like:
invoice 10
USD 8
order 5
And next time I process a file, and check for word frequency, for example:
Counter({'invoice': 2, 'USD': 1, 'tracking': 3})
It should add the count to the words already in the file, and append the new.
So dictionary.txt becomes:
invoice 12
USD 9
order 5
tracking 3
If I try to iterate through the wordscount, I only get the actual word:
for index, wordcount in enumerate(wordscounts):
print(wordcount)
gives me:
invoice
USD
order
But not the word count.
wordscounts- for example, is it a Counter object? if so then you are iterating through the object incorrectly. Also, if you are iterating a dictionary then you are also incorrectly looping.from collections import Counterto my quesiton. Can you elaborate on why I am looping incorrectly?wordscountswas. But, the enumerate wordscounts does not give you the values for the counters. It is the same principle of looping a dict for keys and values. The answer below shows how one can do it.for word, wordcount in wordscounts.items():