2015-02-24 32 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