Answer to Question #167084 in Python for mani

Question #167084

Word Count - 2

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



Sample Input 1

Hello world welcome to python world



Sample Output 1

Hello: 1

python: 1

to: 1

welcome: 1

world: 2


Sample Input 2

This is my book


Sample Output 2

This: 1

book: 1

is: 1

my: 1




1
Expert's answer
2021-02-26T16:14:53-0500
def freq(sentence):
    # Use Python split() to break sentence to word list
    sentence = sentence.split()
    wordList = []

    # Loop through sentence to add each word in sentence to wordList
    for i in sentence:
        if i not in wordList:
            wordList.append(i)

    # Sort word list and assign it to s
    s = sorted(wordList)
    for i in range(0, len(s)):
        # Get frequency of each word
        print(s[i], ':', sentence.count(s[i]))


def main():
    # Prompt user input for string and store in S
    S = input("Enter the sentence to get frequency of each word: ")
    freq(S)


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