Python字符串元音计数器 [英] Python string vowel counter
问题描述
我正在尝试创建一个程序,该程序计算给定情感中的元音数量,并返回最常见的元音,出现的时间和最不常见的元音( s)而忽略那些根本不发生的事件。
这是我当前的代码
I'm trying to create a program that counts the number of vowels in a given sentance and returns the most common occuring vowel(s) and the number of time it(they) occur and the same for the least common vowel(s) whilst ignoring those that do not occur at all. Here is my current code
import collections, string
print("""This program will take a sentence input by the user and work out
the least common vowel in the sentence, vowels being A, E, I, O and U.
""")
sent = None
while sent == None or "":
try:
sent = input("Please enter a sentence: ").lower()
except ValueError:
print("That wasn't a valid string, please try again")
continue
punct = str(set(string.punctuation))
words = sent.split()
words = [''.join(c for c in s if c not in string.punctuation) for s in words]
a = 0
e = 0
i = 0
o = 0
u = 0
for c in sent:
if c is "a":
a = a + 1
if c is "e":
e = e + 1
if c is "i":
i = i + 1
if c is "o":
o = o + 1
if c is "u":
u = u + 1
aeiou = {"a":a, "e":e, "i":i, "o":o, "u":u}
print("The most common occuring vowel(s) was: ", max(aeiou, key=aeiou.get))
print("The least common occuring vowel(s) was: ", min(aeiou, key=aeiou.get))
ender = input("Please press enter to end")
当前,它打印出出现次数最多和最少的元音,而不是全部,它也不会打印出发生的次数,也不会忽略完全不发生的事件。
Currently, it prints out the most and least occuring vowel, not all, and it does not print out the number of occurences either, nor does it ignore those that do not occur at all. Any help as to how I would go about doing this would be appreciated.
谢谢你
推荐答案
vowels = set('aeiou')
counter = collections.Counter(v for v in sentence.lower() if v in vowels)
ranking = counter.most_common()
print ranking[0] # most common
print ranking[-1] # least common
代码上的一些注释。
A few notes on your code.
- 不要使用
a = a + 1
,请使用a + = 1
。 - 不要使用
is
比较字符串,请使用==
:如果c == a:a + = 1
。
- don't use
a = a + 1
, usea += 1
. - don't use
is
to compare strings, use==
:if c == a: a += 1
.
最后,要获得最大值,您需要整个项目,而不仅仅是值。 (不幸的是)这意味着您将需要一个比 aeiou.get
更为复杂的键功能。
Finally, to get the max, you need the entire item, not just the value. This means (unfortunately) that you'll need a more involved "key" function than just aeiou.get
.
# This list comprehension filters out the non-seen vowels.
items = [item for item in aeiou.items() if item[1] > 0]
# Note that items looks something like this: [('a', 3), ('b', 2), ...]
# so an item that gets passed to the key function looks like
# ('a', 3) or ('b', 2)
most_common = max(items, key=lambda item: item[1])
least_common = min(items, key=lambda item: item[1])
lambda
在您看到它的前几次可能会比较棘手。只需注意:
lambda
can be tricky the first few times that you see it. Just note that:
function = lambda x: expression_here
等同于:
def function(x):
return expression_here
这篇关于Python字符串元音计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!