简体   繁体   English

Python字符串元音计数器

[英]Python string vowel counter

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. 关于我将如何执行此操作的任何帮助将不胜感激。

Mant Thanks 谢谢

A collections.Counter would be great here! 一个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 few notes on your code. 有关代码的一些注意事项。

  • don't use a = a + 1 , use a += 1 . 不要使用a = a + 1 ,请使用a += 1
  • don't use is to compare strings, use == : if c == a: a += 1 . 不要使用is比较字符串,请使用==if c == a: a += 1

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 . 这意味着(不幸地)这意味着您将需要更多的“ key”功能,而不仅仅是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 can be tricky the first few times that you see it. 在您看到它的前几次, lambda可能会很棘手。 Just note that: 请注意:

function = lambda x: expression_here

is the same as: 是相同的:

def function(x):
    return expression_here

you can use dictionary: 您可以使用字典:

>>> 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 counts the number of occurrence of element count计算元素的出现次数

you can also do it using list comprehension : 您也可以使用列表理解来做到这一点:

>>> 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]]
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()

From my point of view, just for simplicity, I would recommend you to do it in the following way: 以我的观点,为简单起见,我建议您按以下方式进行操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM