user637965
user637965

Reputation:

word frequency program in python

Say I have a list of words called words i.e. words = ["hello", "test", "string", "people", "hello", "hello"] and I want to create a dictionary in order to get word frequency.

Let's say the dictionary is called 'counts'

counts = {}
for w in words:
    counts[w] = counts.get(w,0) + 1

The only part of this I don't really understand is the counts.get(w.0). The book says, normally you would use counts[w] = counts[w] + 1 but the first time you encounter a new word, it won't be in counts and so it would return a runtime error. That all fine and dandy but what exactly does counts.get(w,0) do? Specifically, what's the (w,0) notation all about?

Upvotes: 1

Views: 13470

Answers (4)

eat
eat

Reputation: 7530

FWIW, with Python 2.7 and above you may prefer to operate with collections.Counter, like:

In []: from collections import Counter
In []: c= Counter(["hello", "test", "string", "people", "hello", "hello"])
In []: c
Out[]: Counter({'hello': 3, 'test': 1, 'people': 1, 'string': 1})

Upvotes: 6

samplebias
samplebias

Reputation: 37919

If you have a dictionary, get() is a method where w is a variable holding the word you're looking up and 0 is the default value. If w is not present in the dictionary, get returns 0.

Upvotes: 7

g.d.d.c
g.d.d.c

Reputation: 48028

The get method on a dictionary returns the value stored in a key, or optionally, a default value, specified by the optional second parameter. In your case, you tell it "Retrieve 0 for the prior count if this key isn't already in the dictionary, then add one to that value and place it in the dictionary."

Upvotes: 0

payne
payne

Reputation: 14187

The dictionary get() method allows for a default as the second argument, if the key doesn't exist. So counts.get(w,0) gives you 0 if w doesn't exist in counts.

Upvotes: 4

Related Questions