2015-02-24 82 views
0

我正在嘗試創建一個分析用戶輸入單詞的工具。它說明了字母的數量(完成),元音的數量(需要幫助),大寫字母的數量(已完成)以及最常見的字母(尚未擔心)。我也做了下面的代碼:Python:創建單詞分析

word = raw_input("Please enter a word:") 
print word 


if len(word) == 1: 
    print word + " has " + str(len(word)) + " letter." 
else: 
    print word + " has " + str(len(word)) + " letters." 


if sum(1 for v in word if v ==["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]) == 1: 
    print "It also has ", sum(1 for v in word if v == ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]), " vowel." 
else: 
    print "It also has ", sum(1 for v in word if v == ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]), " vowels." 


if sum(1 for c in word if c.isupper()) == 1: 
    print "It has ", sum(1 for c in word if c.isupper()), " capital letter." 
else: 
    print "It has ", sum(1 for c in word if c.isupper()), " capital letters." 

使用例如字「你好」,它返回如下:

HeLLo 
HeLLo has 5 letters. 
It also has 0 vowels. 
It has 3 capital letters. 

我很困惑,因爲它知道算元音的數量,包括它在答案中,卻沒有統計單詞中的元音。

我需要做一個小調整還是一個大的改變?

謝謝。

P.S.我如何將問題標記爲已回答?

+1

沒有閱讀完所有的問題,你可能是指'在[「一」,......,「U」]' – 2015-02-24 16:33:06

+0

你的意思,而不是在字v v如果v == [「a」... ... – poddpython 2015-02-24 16:36:47

+0

要解決您的「PS」問題:只需點擊答案旁邊的複選標記符號,以最好地解答您的問題。 – 2015-02-24 16:48:24

回答

2

您正在比較該信與列表。相反,請檢查該信是否爲in該列表。

sum(1 for v in word if v in ["a", more vowels, "U"]) 

此外,您可以通過使用一個字符串,而不是一個列表,並通過套管低信爲先,並沒有重複自己儘可能多的讓你的代碼稍短。

num_vowels = sum(1 for v in word if v.lower() in "aeiou") 
print "It also has ", num_vowels, (" vowel." if num_vowels == 1 else " vowels.") 

爲了找到最常見的字母,你應該使用的字典。只要迭代單詞中的字母並增加它們在字典中的數量,然後選擇數量最高的字母。

counts = {} 
for x in word: 
    counts[x] = counts.get(x, 0) + 1 
print "most common:", max(word, key=lambda x: counts[x]) 

或者只是使用collections.Counter(word).most_common(1)

+0

我現在做了第一段代碼,我仍然拉同樣的錯誤。 「它也有0個元音。」 – poddpython 2015-02-24 16:47:24

+0

您是否在代碼中將'=='全部替換爲三個地方? – 2015-02-24 16:49:13

+0

糟糕...它的工作,也如果你不介意,你能幫我定義最常見的字母嗎?如果沒有,謝謝。 – poddpython 2015-02-24 16:50:42