Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/66059932/how-do-you-locate-check-the-letter-of-each-word-in-a-file-to-see-if-it-is-a-vowe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...