Tuple of tuples with word and its vowel count in a sentence in Python


This Python code processes the sentence and creates a tuple called vowel_count_tuples. Each element in this tuple is a pair containing a word from the sentence and the count of vowels in that word. Here's how the code works:

  • sentence = "Hello, how are you?": This line initializes a variable named sentence and assigns it a string containing the input sentence.
  • vowel_count_tuples = tuple((word, sum(1 for char in word if char.lower() in 'aeiou')) for word in sentence.split()): This line initializes a variable named vowel_count_tuples and assigns it a tuple created using a generator expression.
    • for word in sentence.split(): This part of the code sets up a loop that iterates through each word in the sentence. It does this by splitting the sentence into words using whitespace as the delimiter.
    • (word, sum(1 for char in word if char.lower() in 'aeiou')): For each word, it creates a pair that consists of the word itself and the count of vowels in the word. The count is calculated using the sum(1 for char in word if char.lower() in 'aeiou') expression, which iterates through each character in the word, checks if it's a vowel (case-insensitive), and adds 1 to the count for each vowel found.
    • tuple(...): This surrounds the generator expression and converts the generated pairs into a tuple.
  • print(sentence): This line of code prints the original sentence to the console.
  • print(vowel_count_tuples): This line of code prints the vowel_count_tuples tuple (which contains pairs of words and their vowel counts) to the console.

Source Code

sentence = "Hello, how are you?"
vowel_count_tuples = tuple((word, sum(1 for char in word if char.lower() in 'aeiou')) for word in sentence.split())
print(sentence)
print(vowel_count_tuples)

Output

Hello, how are you?
(('Hello,', 2), ('how', 1), ('are', 2), ('you?', 2))

Example Programs