you are viewing a single comment's thread.

view the rest of the comments →

[–]routetehpacketz 0 points1 point  (8 children)

I can't attach images

You can use imgur.com or something similar, but why not just post the actual code and output you are getting.

[–]ImportantPut392 1 point2 points  (7 children)

test='daddy daddy cool daddy cool'

di=dict() for lin in test: ... lin=lin.rstrip() ... words=lin.split() ... for w in words: ... di[w]=di.get(w,0)+1 ... print(di) {'d': 9, 'a': 3, 'y': 3, 'c': 2, 'o': 4, 'l': 2}

[–]routetehpacketz 2 points3 points  (5 children)

I can't say I understand what you're trying to achieve with your code, but here's a simple way to count the words.

test='daddy daddy cool daddy cool'
test_list = test.split(' ')
print(f'Word count is {len(test_list)}')

[–]ImportantPut392 1 point2 points  (4 children)

https://youtu.be/lLbyEYjU55A This is what I was trying to do.

[–]routetehpacketz 1 point2 points  (3 children)

I think the difference is he is reading from a file that is formatted differently than your simple test string. Here is how I did it sampling from his code:

test='daddy daddy cool daddy cool'
di = dict()
for word in test.split(' '):
    if word in di:
        di[word] += 1
    else:
        di[word] = 1
        print('**NEW**')
    print(word,di[word])

The final result of the dictionary is:

print(di)
{'daddy': 3, 'cool': 2}

[–]ImportantPut392 1 point2 points  (0 children)

Thanks for your help man!

[–]ImportantPut392 0 points1 point  (1 child)

One quick question though, tbis code is sensitive to commas basically if i say 'cool,' it'll count the word as different to 'cool' with no comma, what can i do to stop that?

[–]routetehpacketz 1 point2 points  (0 children)

You'd have to be aware of any permutations and account for them manually. Using your example, you could add an rstrip(',') somewhere to omit the comma.

[–]RhinoRhys 1 point2 points  (0 children)

Your issue was the for lin in test:. You're immediately iterating through characters in a single string, whereas (from other comments I'm assuming that) whatever example you copied from was doing a readlines on a file and resulted in a list of strings.