Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Word Counter Only Counting Words Once

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
like image 453
csstudent2x Avatar asked Aug 11 '26 20:08

csstudent2x


1 Answers

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.

like image 103
IonicSolutions Avatar answered Aug 13 '26 10:08

IonicSolutions



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!