【问题标题】:Python string vowel counterPython字符串元音计数器
【发布时间】:2014-11-12 23:46:12
【问题描述】:

我正在尝试创建一个程序来计算给定句子中元音的数量并返回最常见的元音和它(它们)出现的次数以及最不常见的元音( 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")

目前,它打印出出现次数最多和最少的元音,而不是全部,它也不会打印出现次数,也不会忽略那些根本不出现的元音。任何有关我将如何去做的帮助将不胜感激。

谢谢

【问题讨论】:

    标签: python string counter


    【解决方案1】:

    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
    

    【讨论】:

    • 我投了赞成票,因为它是最 Pythonic 的解决方案。但也许 OP 希望对 他的 代码有所帮助。
    • 超级!现在我相信 OP 得到了最大的帮助。
    • 好吧,这似乎可行,但如果最常见的元音也与最不常见的元音相关联呢?如果根本没有元音怎么办?
    • @RhysTerry -- 嗯,这是你需要弄清楚的事情。在平局的情况下,结果取决于您使用的答案——它可能只会报告一个元音,也可能会任意报告不同的元音。没有元音的情况更容易——您可以尝试/排除处理任何引发的异常(IndexError 在我的第一个答案的情况下,可能ValueError 在我的第二个答案的情况下)。
    【解决方案2】:

    你可以使用字典:

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

    【讨论】:

    • 如果您在理解上有任何问题,请随时询问
    【解决方案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()
    

    【讨论】:

      【解决方案4】:

      从我的角度来看,为了简单起见,我建议您按以下方式进行操作:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-26
        • 1970-01-01
        • 2020-02-19
        • 2011-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多