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
204 views
in Technique[技术] by (71.8m points)

How do I count unique words using counter library in python?

im new to python and trying various libraries

from collections import Counter
print(Counter('like baby baby baby ohhh baby baby like nooo'))

When i print this the output I receive is:

Counter({'b': 10, ' ': 8, 'a': 5, 'y': 5, 'o': 4, 'h': 3, 'l': 2, 'i': 2, 'k': 2, 'e': 2, 'n': 1})

But I want to find the count of unique words:

#output example
({'like': 2, 'baby': 5, 'ohhh': 1, 'nooo': 1}, ('baby', 5))

How can I do this, additionally can I do this without the counter library using loops?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The python Counter class takes an Iterable object as parameter. As you are giving it a String object:

Counter('like baby baby baby ohhh baby baby like nooo')

it will iterate over each character of the string and generate a count for each of the different letters. Thats why you are receiving

Counter({'b': 10, ' ': 8, 'a': 5, 'y': 5, 'o': 4, 'h': 3, 'l': 2, 'i': 2, 'k': 2, 'e': 2, 'n': 1})

back from the class. One alternative would be to pass a list to Counter. This way the Counter class will iterate each of the list elements and create the count you expect.

Counter(['like', 'baby', 'baby', 'baby', 'ohhh', 'baby', 'baby', 'like', 'nooo'])

That could also be simply achived by splitting the string into words using the split method:

Counter('like baby baby baby ohhh baby baby like nooo'.split())

Output

Counter({'baby': 5, 'like': 2, 'ohhh': 1, 'nooo': 1})

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

...