I want to count the number of times a word occur in a list of sting.
['this is a red ball','this is another red ball']
I wrote the following code
counts = Counter()
for sentence in lines:
counts.update(word.strip('.,?!"\'').lower() for word in sentence.split())
It gives me a result in the following format
Counter({'': 6, 'red': 2, 'this': 2, ....})
How can I only get the dictionary?
We are going to make a constructor of the dictionary so that using objects of the counter we can directly convert it into Dictionary. # Creating dictionary b # Here dict () constructor is used to make a new dictionary b=dict (a) ## Printing Dictionary b print ("Dictionary is ",b)
Though you will have all the operations in countsvariable which you can do in a normal python dictionary because Counteris a subclass of dict. From Counterdocs:
Python | Counter Objects | elements() Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python’s general purpose built-ins like dictionaries, lists and tuples.
Once a Counter is populated, its values can be retrieved using the dictionary API. Counter does not raise KeyError for unknown items. its count is 0. For Python training, our top recommendation is DataCamp. times as its count. Elements are returned in arbitrary order.
You can just do the following if a dictionary is really what you want.
dict(counts)
Though you will have all the operations in counts
variable which you can do in a normal python dictionary because Counter
is a subclass of dict
.
From Counter
docs:
A
Counter
is adict
subclass for counting hashable objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With