2013-11-01 52 views
0

我發現了一些這樣的例子,但是我的問題稍有不同。在一個句子中計算特定元音

我需要掃描一句話

For letter in sentence 
if letter == "a" or letter == "A": letterATotal = letterATotal + 1 
elif letter == "e" or letter == "E": letterETotal = letterETotal + 1 

等一路U. 但我需要比較他們都和打印包含最頻繁的所以 行「最頻繁的元音發生5次「。 問題是我不知道如何顯示實際的字母。我只能顯示數字。 有什麼建議嗎?

回答

4

看看這個:

>>> from collections import Counter 
>>> mystr = "AaAaaEeEiOoouuu" 
>>> a,b = Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)[0] 
>>> "the most frequent vowel is {} occurring {} times".format(a.upper(), b) 
'the most frequent vowel is A occurring 5 times' 
>>> 

這裏是collections.Counter參考。


編輯:

這是怎麼回事的一步一步的示範:

>>> from collections import Counter 
>>> mystr = "AaAaaEeEiOoouuu" 
>>> Counter(c for c in mystr.lower() if c in "aeiou") 
Counter({'a': 5, 'o': 3, 'e': 3, 'u': 3, 'i': 1}) 
>>> # Get the top three most common 
>>> Counter(c for c in mystr.lower() if c in "aeiou").most_common(3) 
[('a', 5), ('o', 3), ('e', 3)] 
>>> # Get the most common 
>>> Counter(c for c in mystr.lower() if c in "aeiou").most_common(1) 
[('a', 5)] 
>>> Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)[0] 
('a', 5) 
>>> a,b = Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)[0] 
>>> a 
'a' 
>>> b 
5 
>>> 
+0

你好,謝謝你這個完美的作品!你能解釋一下櫃檯是如何爲我工作的嗎?特別是a,b =和最後的方括號。 – JamesDonnelly

+1

@JamesDonnelly - 對,遲到對不起。我在我的文章中包含了一個分步演示。 – iCodez

+0

你可以解釋一下這行(c在mystr.lower()中是否存在,如果c在「aeiou」中)?謝謝 – JamesDonnelly

2

使用collections.Counter

>>> from collections import Counter 
>>> c = Counter() 
>>> vowels = {'a', 'e', 'i', 'o', 'u'} 
for x in 'aaaeeeeeefffddd': 
    if x.lower() in vowels: 
     c[x.lower()] += 1 
...   
>>> c 
Counter({'e': 6, 'a': 3}) 
>>> letter, count = c.most_common()[0] 
>>> letter, count 
('e', 6) 
-2

通過句子字符串的子串,並遞增整數數組索引0-4(對於AU) 末找到陣列的最大值,並將它打印正確的說法

0

下面的代碼工作,如果你正在使用Python 3或以上:

s = input ('Enter a word or sentence to find how many vowels:') 

sub1 = 'a' 
sub2 = 'e' 
sub3 = 'i' 
sub4 = 'o' 
sub5 = 'u' 

print ('The word you entered: ', s) 

print ('The count for a: ', s.count(sub1)) 

print ('The count for e: ', s.count(sub2)) 

print ('The count for i: ', s.count(sub3)) 

print ('The count for o: ', s.count(sub4)) 

print ('The count for u: ', s.count(sub5))