115k views
3 votes
This is in Python 3:Assign to a variable in your program a triple-quoted string that contains your favourite paragraph of text — perhaps a poem, a speech, instructions to bake a cake, some inspirational verses, etc.Write a function which removes all punctuation from the string, breaks the string into a list of words, and counts the number of words in your text that contain the letter "e". Your program should print an analysis of the text like this:Your text contains 243 words, of which 109 (44.8%) contain an "e".

1 Answer

4 votes

Final answer:

To complete this task, you can assign a triple-quoted string to a variable in Python 3. Write a function that removes punctuation, splits the string into words, and counts the number of words with the letter 'e'. Finally, print the analysis of the text.

Step-by-step explanation:

To complete this task, you can start by assigning your favorite paragraph of text to a variable using triple quotes in Python 3. Then, write a function that removes all punctuation from the string using the 'translate' method and 'string.punctuation' constant. Next, split the string into a list of words using the 'split' method. Finally, use a loop and the 'in' keyword to check if each word contains the letter 'e' and keep a count. Print the total number of words and the percentage of words with 'e' using the count and the length of the list.

For example:

import string

def count_words_with_e(text):

cleaned_text = text.translate(str.maketrans('', '', string.punctuation))

word_list = cleaned_text.split()

total_words = len(word_list)

words_with_e = sum('e' in word for word in word_list)

percentage_with_e = (words_with_e / total_words) * 100

print(f"Your text contains {total_words} words, of which {words_with_e} ({percentage_with_e:.1f}%) contain an 'e'.")
User Grasevski
by
7.6k points