当用户输入单词Python时如何分离元音和常量

时间:2015-11-02 22:38:31

标签: python string input

编写一个程序,让你输入一个单词,打印出元音的数量和辅音的数量(元音是:a,e,i,o,u。所有其他都是辅音)。该程序应重复询问更多单词,直到您输入“停止” 提示:在find()函数中使用build。

这是我到目前为止所做的:

word = raw_input('Enter a word')
print word.find("a"), word.find("e"), word.find('i'), word.find('o'), word.find('u')

我真的迷失了下一步该做什么可以有人告诉我如何正确使用find功能,因为它似乎没有像我期望的那样工作,但事实并非如此。在这段代码中,我需要使用.find()内置函数,而不使用if语句并查找值是'a'还是'e'等等!

4 个答案:

答案 0 :(得分:2)

getinput=""
while getinput != "stop":
    getinput=raw_input("Enter a word: ")
    vowels=len([v for v in getinput if v in "aeiou"])
    consonants=len([v for v in getinput if v not in "aeiou"])
    print("No. of vowels in this word:",vowels)
    print("No. of consonants in this word:",consonants)

python2.7脚本

答案 1 :(得分:1)

使用正则表达式。在这种情况下,它简化了事情。

import re
word = raw_input('Enter a word')
numvowels = len(re.findall("[aeiou]", word))
numconsonants = len(word) - numvowels
print("Number of vowels is {} and number of consonants is {}".format(numvowels, numconsonants))

答案 2 :(得分:0)

您应该尝试使用循环,以便用户可以编写多个条目,并计算元音的数量。或者尽可能使用函数计数

答案 3 :(得分:0)

写完一个问题并发布一些代码做得很好。

你没有说出你期望的find()做什么,但我想你会期望它能回报它发现了多少次?不; count()这样做;你可以(word.count('a') + word.count('e')...)来解决这个问题,但你的提示是使用find(),这样就可以了。

find()返回 找到的东西,如果找不到则返回-1。

你将需要word.find('a')然后存储结果,检查它是否是字符串中的位置或-1表示它什么也没找到。然后word.find('a', location+1)从搜索位置后搜索,并搜索剩余的字符。检查它的返回值,看它是否找到了什么,然后继续循环,直到找不到任何东西。跟踪它循环的次数。

然后为“e”,“我”,“o”,“你”这样做。 (循环内的循环)。

将它们全部添加,这就是元音的数量。取len(word) - num_vowels,这就是辅音的数量......

未完成的例子:

word = 'alfalfa'

location = word.find('a')
if location > -1: 
    print 'found "a", count this'

while location > -1:
    location = word.find('a', location + 1)
    if location > -1:
        print 'found another "a", count this'