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
import sys
import string
print('Enter a sentence:')
S = sys.stdin.readline()
words = S.split()
d = {}
for w in words:
if w[-1] in string.punctuation:
w = w[:-1]
if w in d:
d[w] += 1
else:
d[w] = 1
print('\nThe word frequency is:')
for w in sorted(d):
print(f'{w}: {d[w]}')
Comments
Leave a comment