-2

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!!!

6
  • 2
    Please paste the error message instead of including an image. (See How to Ask.) Commented Feb 18, 2021 at 14:37
  • what is the output of wordlist_freq['je'] ? Commented Feb 18, 2021 at 14:37
  • What is all_words. Is it a list or is it a string with words separated by spaces? That matters here. Commented Feb 18, 2021 at 14:44
  • freq['je'] = wordlist_freq.get('je',0) same for the other - in case you do not have the word you'll get a KeyError otherwise# Commented Feb 18, 2021 at 14:44
  • I don't get KeyError when all_words contain je. Commented Feb 18, 2021 at 15:05

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.