Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

list - How to count word dictionary in Python?

I have a question about dictionary handling in Python.

I wonder how to compare the dictionary with the list of words.

[example of my input]

text = ['fall', 'big', 'pocket', 'layer', 'park', ...]
mylist = ['spring', 'summer', 'fall', 'winter', 'school', ...]

[make dictionary code]

lst_dic = {mylist : 0 for mylist in mylist }
lst_dic

I want to know how many words matching in mylist from text.

[fail code]

lst_dic = {}
for w in mylist:
    if w in text_1_1:
        lst_dic[w] += 1
    else:
        lst_dic[w] = 0

As a result, I want to know dictionary key and value. Like this:

{ 'spring':0,
  'summer':3,
  'fall':1,
  'winter':0,
  ...
}

Then, I want to extract more than 10 count value of attributes.

Please take a look at this issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code isn't initializing the lst_dic correctly in the case of the first time a key (word) occurs in the mylist. Hence, you get a KeyError.

Use collections.defaultdict to initialize the dictionary instead. This allows you to remove the else branch from your code, and merely increment each time you encounter the frequency a word in text.

import collections

text = ['fall', 'big', 'pocket', 'layer', 'park']
mylist = ['spring', 'summer', 'fall', 'winter', 'school']

lst_dic = collections.defaultdict(int)
for w in mylist:
    if w in text:
        lst_dic[w] += 1

# Show the counts of all `text` words occurring in `mylist`:
print(dict(lst_dic))

# Extract those with counts > 10:
print([e for e in lst_dic if lst_dic[e] > 10])

# Or, if you want it as a dictionary:
print({e: lst_dic[e] for e in lst_dic if lst_dic[e] > 10})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...