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
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()
Comments
Leave a comment