In: Computer Science
Make sure to include comments that explain all your steps (starts with #)
Make sure to include comments that explain all your steps (starts with #)
Write a program that prompts the user for a string (a sentence, a word list, single words etc.), counts the number of times each word appears and outputs the total word count and unique word count in a sorted order from high to low. The program should: Display a message stating its goal Prompt the user to enter a string Count the number of times each word appears in the string, regardless if in lowercase or uppercase (hint: use dictionaries and the lower() function) Display the total number of words in the string Display the unique word count in the string in order from high to low Bonus: if a few words have the same count, sort the display in an alphabetic order For example, in the string: “Hello hello my dear dear friend!” the output should be: Total words: ========= 6 Word count: ========= dear - 2 hello - 2 friend - 1 my - 1
text=input('Enter text: ')
total=0
d={}#dictionary to store frequency
for i in text.split():#split by space, and iterate
word=i.lower().strip(";:,.?!")#convert to lowercase, remove common
punctuations from start and end
if word in d:
d[word]+=1#if word is in dictionary, add 1 to count
else:
d[word]=1#if not, add to dictionary with count 1
total+=1#increment total
print('Total words:',total)
print("="*10)
print('Word count')
print("="*10)
for i in sorted(d,key=lambda x: (-d[x],x)):#sort dictionary keys,
first by the dicitonary value, then the key itself
#the key above specified wat is to be compared
print(i,"-",d[i])