Question: Here's a Python program that reads multiple lines of plain text from the user and counts the occurrences of each word. The words are listed

Here's a Python program that reads multiple lines of plain text from the user and counts the occurrences of each word. The words are listed in alphabetical order.
# Initialize a dictionary to store word counts
word_counts ={}
# Read multiple lines of input from the user until an empty line is entered
while True:
line = input("Enter line: ")
if line =="":
break
# Split the line into words
words = line.split()
# Update the word counts
for word in words:
if word in word_counts:
word_counts[word]+=1
else:
word_counts[word]=1
# Get the words in alphabetical order
sorted_words = sorted(word_counts.keys())
# Print the word counts in alphabetical order
for word in sorted_words:
print(f"{word}{word_counts[word]}")
1st step:
A dictionary word_counts is initialized to store the count of each word.
A while loop is used to read multiple lines of input until an empty line is entered.
Each line is split into words using split().
For each word in the line, the count is updated in the word_counts dictionary.
After all input lines are processed, the words are sorted alphabetically using sorted().
The sorted words and their counts are printed.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!