I'm trying to make a Python word counter that counts words from a file that was inputted into a dictionary. However, my counter only counts the word once and I'm not sure why. Also, would there be a way not to use the collection Counter ?
cloud = {}
val = 0
with open('objects.txt', 'r') as file:
for line in file:
for thing in line:
new_thing = thing.strip(' ')
cloud[new_thing] = val
for new_thing in cloud:
cloud[new_thing] = cloud.get(new_thing, val) + 1
In your code, for each new line, you set
cloud[new_thing] = 0
which resets the counter for the word new_thing.
Since you already use cloud.get(new_thing, 0) which will return 0 if the key new_thing is not found, you can just remove that line.
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