简体   繁体   English

您如何定位/检查文件中每个单词的字母以查看它是元音还是辅音?

[英]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.与 Python 中的任何其他序列一样,字符串是可下标的。

So for a word, you can get the first letter by doing word[0]所以对于一个单词,你可以通过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:您需要 select 单词中的第一个字符并将其与元音数组进行比较,或者您可以使用 startswith() 方法:

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. text.split() 将返回一个单词数组。 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.而不是word.startswith()您也可以在链接的帖子中使用该解决方案。

for word in text:
    if word[0].lower() in ['a', 'e', 'i', 'o', 'u']:
        print("It's a vowel")
    else:
        print("Not a vowel")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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