pythonscrub
pythonscrub

Reputation: 75

Occurrence count on text file not working when trying to make a dictionary

I have a text file that looks like this:

'Bill','Bill','Bill','Jake','Jake','Mike','Mike','Mike','Mike'

I am trying to count the number occurrences for each name. These names can always change so I can't hard code them. I've seen other examples that were formatted differently and I tried to replicate my code as close as possible, but it still doesn't work.

My code:

text = open("test.txt", "r") 

d = dict() 

for line in text: 

    line = line.strip()
    line = line.lower()
    line = line.replace('"', '').replace("'", "")
    words = line.split(" ") 

    for word in words:

        if word in d: 
            d[word] = d[word] + 1
        else: 
            d[word] = 1

for key in list(d.keys()): 
    print(key, ":", d[key])  

My output:

'Bill','Bill','Bill','Jake','Jake','Mike','Mike','Mike','Mike',: 1

Upvotes: 0

Views: 31

Answers (1)

sophros
sophros

Reputation: 16620

You are splitting by space which is absent in the lines (but comma is there).

Try changing:

words = line.split(" ") 

to:

words = line.split(",") 

Upvotes: 1

Related Questions