I have a list of words in a dictionary with the value = the repetition of the keyword but I only want a list of distinct words so I wanted to count the number of keywords. Is there a way to count the number of keywords or is there another way I should look for distinct words?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
len(yourdict.keys())
or just
len(yourdict)
If you like to count unique words in the file, you could just use set
and do like
len(set(open(yourdictfile).read().split()))
回答2:
The number of distinct words (i.e. count of entries in the dictionary) can be found using the len()
function.
> a = {'foo':42, 'bar':69}
> len(a)
2
To get all the distinct words (i.e. the keys), use the .keys()
method.
> list(a.keys())
['foo', 'bar']
回答3:
If the question is about counting the number of keywords then would recommend something like
def countoccurrences(store, value):
try:
store[value] = store[value] + 1
except KeyError as e:
store[value] = 1
return
in the main function have something that loops through the data and pass the values to countoccurrences function
if __name__ == "__main__":
store = {}
list = ('a', 'a', 'b', 'c', 'c')
for data in list:
countoccurrences(store, data)
for k, v in store.iteritems():
print "Key " + k + " has occurred " + str(v) + " times"
The code outputs
Key a has occurred 2 times
Key c has occurred 2 times
Key b has occurred 1 times