Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...