2015-11-02 47 views
-2

編寫一個程序,讓您輸入一個單詞並打印出元音的數量和輔音的數量(元音是:a,e,i,o,所有其他人都是輔音)。程序應該重複詢問更多的單詞,直到你輸入「stop」 提示:使用find()函數構建。當用戶輸入一個單詞時如何分離元音和常量Python

這是我到目前爲止有:

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

我真的失去了爲下一步做什麼可以有人告訴我如何正確地使用查找功能,因爲它似乎不被工作我期待它的工作方式,但事實並非如此。在這段代碼中,我需要使用.find()內置函數,而不使用if語句並查找值是'a'還是'e'等等!

回答

0

好寫一個問題,有一些代碼後完成的功能計數。

你沒有說你期望find()要做什麼,但我想你會期望它返回多少次它發現了什麼?不; count()這樣做;你可以(word.count('a') + word.count('e')...)來解決這個問題,但你的提示是使用find(),所以這樣。

find()返回其中它找到了一些東西,或-1,如果它什麼都沒找到。

你將不得不word.find('a'),然後存儲結果,檢查它是否在字符串中的位置或-1以表示它什麼都沒找到。然後word.find('a', location+1)從查找位置後面搜索,然後搜索剩餘的字符。檢查它的返回值,看它是否發現任何東西,然後繼續循環,直到找不到任何東西。跟蹤它的循環次數。

然後爲'e','i','o','u'做那個。 (循環內的一個循環)。

把它們全部加起來,這就是元音的數量。就拿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' 
+0

謝謝,這真的很有幫助!我剛剛得到了一個問題,爲什麼我需要做一個循環,我不能這樣做。find()然後將所有值一次存儲,因爲函數不會在函數中找到每個'a'? – pythonguy

+0

*這個函數不會在函數中找到每個'a'嗎?* - 不,它不會; 'help(word.find)>內建函數find的幫助:返回S中找到substring sub的最小索引 - 它返回一個結果,它找到第一個結果。 – TessellatingHeckler

+0

好吧,那麼我應該在if語句中使用while循環,直到.find()找不到更多的元音?我很困惑:( – pythonguy

0

您應該嘗試使用循環,以便用戶可以寫入多個條目並計算元音的數量。或者使用如果可能的話

+0

是但像這個問題說,我需要使用the.find()函數來找到他們,我不知道該怎麼做... – pythonguy

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腳本

+0

這工作,但你知道如何使用做.find()內置函數? – pythonguy

+1

使用.find()方法將返回一個索引號,該索引號描述了模式在輸入字符串中的位置,因此它不會輸出模式的出現次數。 .find()==不合適 – repzero

+0

但是沒有辦法統計有多少個索引有元音?或者有多少個索引被發現是元音? – pythonguy

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)) 
+0

很好用正則表達式 – repzero

相關問題