【问题标题】:Count the amount of vowels in a sentence and display the most frequent统计句子中元音的数量并显示出现频率最高的
【发布时间】:2013-11-24 21:06:10
【问题描述】:

到目前为止,这是我计算元音的代码。我需要浏览一个句子,计算和比较元音,然后显示出现频率最高的元音。

from collections import Counter
vowelCounter = Counter()
sentence=input("sentence")
for word in sentence:
    vowelCounter[word] += 1
vowel, vowelCount= Counter(vowel for vowel in sentence.lower() if vowel in "aeiou").most_common(1)[0]

有人有更好的方法吗?

【问题讨论】:

  • 问题到底是什么?
  • 为什么你有 for 循环和vowel, vowelCount= 行?在我看来,后一行将按原样解决您的问题。
  • 你可以先排序,然后在O(n)时间内扔掉
  • @DavidRobinson 有没有办法提取最常见的前 5 个变量并将它们设置为不同的变量,如 vowelA、countA、vowelB 和 CountB 等?

标签: python counter counting


【解决方案1】:

IMO,为了清楚起见,最好避免使用长行:

#!/usr/local/cpython-3.3/bin/python

import collections

sentence = input("sentence").lower()
vowels = (c for c in sentence if c in "aeiou")
counter = collections.Counter(vowels)
most_common = counter.most_common(1)[0]
print(most_common)

【讨论】:

    【解决方案2】:

    如果你所追求的只是 max-occurrent 元音,那么你真的不需要Counter

    counts = {i:0 for i in 'aeiou'}
    for char in input("sentence: ").lower():
      if char in counts:
        counts[char] += 1
    print(max(counts, key=counts.__getitem__))
    

    【讨论】:

    • 你应该使用counts[char] = counts.get(char, 0) + 1
    • @hcwhsa:感谢您的错误报告。我只寻找元音,这就是我初始化dict 的原因;但我确实忘记了一个 if 语句
    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 2019-08-15
    • 2012-11-03
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多