简体   繁体   中英

How do you locate/check the letter of each word in a file to see if it is a vowel or consonant?

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!!

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)

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")

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM