3

I wanted to create a code that printed the frequency of words in a string and I did but I had a little problem though. Here's the code:

string=input("Enter your string: ")
string=string.split()
a=0
while(a<len(string)):
     print (string[a], "=", string.count(string[a]))
     a=a+1

Everything ran fine but if a word occurred twice, it'd say the word and state the occurrence in two places. I really need help here. Thanks!

1

1 Answer 1

1

You can get rid of duplicates in a string by using set() and only iterate through unique strings:

s=input("Enter your string: ")
s=s.split()

for i in set(s):
    print(i, "=", s.count(i)

Alternatively you can use collections.Counter():

from collections import Counter

s=input("Enter your string: ")
s=s.split()

for key, value in Counter(s).items():
    print(key, "=", value)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks that really helped a lot Finally did it
I'm happy to help :). If this solution solved your problem you can mark it as accepted by clicking the checkmark next to it. Cheers!
Note: it would probably be a good idea not to name your variable string there is a standard string module this would hide.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.