Answer to Question #165073 in Python for teja

Question #165073

Given a sentence S, write a program to print the frequency of each word in S, where words are sorted in alphabetical order.Input


The input will be a single line containing a string S.Output


The output contains multiple lines, with each line containing a word and frequency of each word in the given string separated by ": ", where words are sorted in alphabetical order.Explanation


For example, if the given sentence is "Hello world, welcome to python world", the output should be

Hello: 1

python: 1

to: 1

welcome: 1

world: 2


1
Expert's answer
2021-02-19T07:46:08-0500
def freq(str): 
  
    # break the string into list of words  
    str = str.split()          
    str2 = [] 
  
    # loop till string values present in list str 
    for i in str:              
  
        # checking for the duplicacy 
        if i not in str2: 
  
            # insert value in str2 
            str2.append(i)  
    
    # sorting list
    s = sorted(str2)
    for i in range(0, len(s)): 
  
        # count the frequency of each word(present  
        # in str2) in str and print 
        print( s[i], ':', str.count(s[i]))     
  
def main(): 
    str = input("Enter the sentence: ")
    freq(str)                     
  
if __name__=="__main__": 
    main()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS