【问题标题】:How do you locate/check the letter of each word in a file to see if it is a vowel or consonant?您如何定位/检查文件中每个单词的字母以查看它是元音还是辅音?
【发布时间】:2021-02-05 08:27:54
【问题描述】:

基本上,我有一个文本文件。我需要能够检查文本文件中的每个单词,以查看该单词是否以元音或辅音开头。

我使用此代码读取文件,然后将文件拆分为单词列表:

with open("textfile.txt") as file:
     text = file.read()
     text = text.split()

但是,我不确定如何深入到字母级别并对每个单词进行元音/辅音检查。如何检查列表中每个单词的第一个字母,看它是元音还是辅音?

这篇文章告诉我如何检查元音: checking if the first letter of a word is a vowel

所以我的问题真的是,如何在单词/字母级别进行检查?

谢谢!!

【问题讨论】:

  • 嗨希尔伯特!你能分享你的文件的内容吗?我怀疑您需要按行拆分text.split('\n')。谢谢。

标签: python python-3.x list


【解决方案1】:

与 Python 中的任何其他序列一样,字符串是可下标的。

所以对于一个单词,你可以通过word[0]得到第一个字母

然后,从其他你已经知道的其他帖子中,如何检查它是元音还是辅音。

您可以通过循环遍历文本中的每个单词来执行此操作。

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)

【讨论】:

    【解决方案2】:

    您需要选择单词中的第一个字符并将其与元音数组进行比较,或者您可以使用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")
    

    【讨论】:

      【解决方案3】:

      text.split() 将返回一个单词数组。您需要对其进行迭代并检查每个单词是否以元音开头。

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

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

      【讨论】:

        猜你喜欢
        • 2023-02-03
        • 2020-06-20
        • 1970-01-01
        • 2022-11-17
        • 2012-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-10
        相关资源
        最近更新 更多