Search code examples
pythonfrequency

How to create a program in python that prints the number of occurrence of words in a string


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!


Solution

  • 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)