【问题标题】:Need to find vowels inside of a word [duplicate]需要在单词中找到元音[重复]
【发布时间】:2014-11-05 01:16:54
【问题描述】:

任何帮助、解释、教程,将不胜感激,谢谢。

【问题讨论】:

标签: python python-2.7 loops while-loop


【解决方案1】:

这应该可以帮助您入门。但是你真的应该自己做功课。

 word="homework"
 vowels=['a','e','i','o','u']
 print len([x for x in word if x in vowels]) # number of vowels
 print len([x for x in word if x not in vowels]) # number of consonants

我们使用了 python 的两个有趣的特性:集合操作(​​x in vowels)和列表推导 [x for x in ....]。列表推导消除了其他人可能建议的那些混乱的显式循环。

【讨论】:

  • 您也可以只打印 len(word) - vowel_count 的辅音,以节省循环单词两次。
【解决方案2】:
while True: #@ 1
    vowels = 0 #@ 2
    consonants = 0
    word = raw_input(">>Enter a word: ").lower() #@ 3
    if word != "stop": #@ 4
        for letter in word: #@5
            if letter in ["a", "e", "i", "o", "u"]:
                vowels += 1
            else:
                consonants += 1

        print "Vowels: ", vowels
        print "Consonants: ", consonants
    else: #@ 6
        break

解释:

@1 使这个程序永远循环

@2 将元音和辅音计数重置为 0

@ 3 用户输入,.lower() 使这个词小写以避免有'A'和'a'。

@ 4 如果这个词不是“停止”,它将继续计数

@ 5 个循环遍历单词中的每个字母,如果符合条件,则增加元音/辅音

@ 6 如果单词是“停止”,则程序结束。

【讨论】:

  • 非常感谢,正是我一直在寻找的东西,现在我要读一遍,看看你背后的思考过程。
  • 刚刚添加了解释。
  • 更好,非常感谢。
【解决方案3】:
def vowelTest():
    vowels = ['a','e','i','o','u']
    isVowel, isNot = "vowel", "not vowel"
    result = []
    code = input()i
    code = code.lower()
    while code != "stop":
        if len(code):
            for item in code:
                if item in code:
                    result.append((item,isVowel))
                else:
                    result.append((item,isNot))
        print(result)
        code = input()
        code = code.lower()


vowelTest() 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-10
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    相关资源
    最近更新 更多