pythonfrench

how to count the frequency of a given word in python


I want to find the frequency of the words "je" and "nous" in 75 texts.

In fact, I know how to make frequency lists at one time by importing os and so on. But this time, what I need, it's just the respective frequency of the two words.

And I tried to change the code of making frequency lists to achieve my goal but failed.

here is a part of my code:

wordlist_freq={}
for word in all_words:
    if word in wordlist_freq.keys():
        wordlist_freq[word] +=1
    else:
        wordlist_freq[word] =1

freq = {}

freq['je']=wordlist_freq['je']
freq['nous']=wordlist_freq['nous']

output[name]=wordlist_freq.items()

and it shows a KeyError: 'je'
error

I really can't understand it and my current idea is too stupid because I want to make a frequency list and then extra the frequency of "je" and "nous". There should be some easier solutions!!!

Please help me~ Thank you!!!


Solution

  • You can use Counter from collections for this

    from collections import Counter
    
    word_list = ["hi", "hi", "je", "nous", "hi", "je", "je"]
    wordlist_freq = Counter(word_list)
    

    In order to get the frequency of a word, you can use get method like this

    wordlist_freq.get("je", 0)
    

    I prefer using get instead of square brackets because get can return a default value when the word is absent in the Counter object.

    If you choose not to use Counter and want to use the loop you shared in Q, you can still do that. But make sure that you get method on the dict to handle the cases where the word is not present in the dict.