Python字符串元音计数器

时间:2014-11-12 23:46:13

标签: python string counter

我正在尝试创建一个程序来计算给定发送中元音的数量,并返回最常见的发生元音及其发生的时间(对于最不常见的元音)相同( s)而忽略那些根本没有发生的那些。 这是我目前的代码

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")

目前,它打印出最多和最少发生的元音,而不是全部,并且它也不会打印出发生的次数,也不会忽略那些根本不发生的元音。如何帮助我做这件事将不胜感激。

谢谢

4 个答案:

答案 0 :(得分:4)

这里的collections.Counter会很棒!

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 = a + 1,请使用a += 1
  • 请勿使用is来比较字符串,请使用==if c == a: a += 1

最后,要获得最大值,您需要整个项目,而不仅仅是价值。这意味着(不幸的是)你需要一个更加复杂的关键"功能而不仅仅是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可能会很棘手。请注意:

function = lambda x: expression_here

与:

相同
def function(x):
    return expression_here

答案 1 :(得分:0)

你可以使用字典:

>>> a = "hello how are you"
>>> vowel_count = { x:a.count(x) for x in 'aeiou' }
>>> vowel_count 
{'a': 1, 'i': 0, 'e': 2, 'u': 1, 'o': 3}
>>> keys = sorted(vowel_count,key=vowel_count.get)
>>> print "max -> " + keys[-1] + ": " + str(vowel_count[keys[-1]])
max -> o: 3
>>> print "min -> " + keys[0] + ": " + str(vowel_count[keys[0]])
min -> i: 0

count计算元素的出现次数

你也可以使用列表理解来做到这一点:

>>> vowel_count = [ [x,a.count(x)] for x in 'aeiou' ]
>>> vowel_count
[['a', 1], ['e', 2], ['i', 0], ['o', 3], ['u', 1]]
>>> sorted(vowel_count,key=lambda x:x[1])
[['i', 0], ['a', 1], ['u', 1], ['e', 2], ['o', 3]]

答案 2 :(得分:0)

class VowelCounter:
    def __init__(self, wrd):
        self.word = wrd
        self.found = 0
        self.vowels = "aeiouAEIOU"
    def getNumberVowels(self):
        for i in range(0, len(self.word)):
            if self.word[i] in self.vowels:
                self.found += 1
        return self.found

    def __str__(self):
        return "There are " + str(self.getNumberVowels()) + " vowels in the String you entered."
def Vowelcounter():
    print("Welcome to Vowel Counter.")
    print("In this program you can count how many vowel there are in a String.")
    string = input("What is your String: \n")
    obj = VowelCounter(string)
    vowels = obj.getNumberVowels()
    if vowels > 1:
        print("There are " + str(vowels) + " vowels in the string you entered.")
    if vowels == 0:
        print("There are no vowels in the string you entered.")
    if vowels == 1:
        print("There is only 1 vowel in the string you entered.")
    recalc = input("Would you like to count how many vowels there are in a different string? \n")
    if recalc == "Yes" or recalc == "yes" or recalc == "YES" or recalc == "y" or recalc == "Y":
        Vowelcounter()
    else:
        print("Thank you")
Vowelcounter()

答案 3 :(得分:0)

以我的观点,为简单起见,我建议您按以下方式进行操作:

 def vowel_detector():
        vowels_n = 0
        index= 0
        text = str(input("Please enter any sentence: "))
        stop = len(text)
        while index != stop:
            for char in text:
                if char == "a" or char == "e" or char == "i" or char=="o" or char == "u":
                    vowels_n += 1
                    index += 1
                else: 
                    index +=1




          print("The number of vowels in your sentence is " + str(vowels_n))
        return

    vowel_detector()