Reputation: 5
Basically, I have a text file. I need to be able to check each word in the text file to see if the word starts with a vowel or consonant.
I used this code to read and then split the file into a list of words:
with open("textfile.txt") as file:
text = file.read()
text = text.split()
However from this, I am unsure how to drill down to the letter level and make the vowel/consonant check on each word. How do I check the first letter of each word in the list to see if it is a vowel or consonant?
This post tells me how to check for vowels: checking if the first letter of a word is a vowel
So my question really is, how do I make the check on the word/letter level?
Thanks!!
Upvotes: 0
Views: 559
Reputation: 2343
A string, alike any other sequence in Python, is subscriptable.
So for a word, you can get the first letter by doing word[0]
Then, from other other post you already know, how to check if it is vowel or consonant.
You can do that for every word in your text by looping over them.
words_starting_with_vowels = []
words_starting_with_consonants = []
vowels = ['a', 'e', 'i', 'o', 'u']
for word in text: # loop over all words
lower_case_letter = word[0].lower()
if lower_case_letter in vowels:
words_starting_with_vowels.append(word)
else:
words_starting_with_consonants.append(word)
Upvotes: 1
Reputation: 156
text.split() will return an array of words. You need to iterate over this and check if each word starts with a vowel.
for word in text:
if word.startswith(('A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u')):
print("It's a vowel") # Or do something else with the word
else:
print("Not a vowel")
Instead of word.startswith()
You could also use the solution in the post you linked.
for word in text:
if word[0].lower() in ['a', 'e', 'i', 'o', 'u']:
print("It's a vowel")
else:
print("Not a vowel")
Upvotes: 0
Reputation: 1908
You need to select the first character in your word and compare it against an array of vowels, or you can use the startswith() method:
vowels = ('a','e','i','o','u','A','E','I','O','U')
if text.startswith(vowels):
print("starts with vowel")
else:
print("starts with consonant")
Upvotes: 0