【问题标题】:Get frequency of letters in a sentence获取句子中字母的频率
【发布时间】:2018-05-19 18:01:12
【问题描述】:

我正在尝试编写一个代码,我可以在其中输入一个随机句子,并计算一个字母在此字符串中返回的次数:

def getfreq(lines):
    """ calculate a list with letter frequencies

    lines - list of lines (character strings)

    both lower and upper case characters are counted.
    """
    totals = 26*[0]
    chars = []
    for line in lines:
       for ch in line:
           chars.append(totals)

    return totals

    # convert totals to frequency
    freqlst = []
    grandtotal = sum(totals)

    for total in totals:
        freq = totals.count(chars)
        freqlst.append(freq)
    return freqlst

到目前为止,我已经将输入的每个字母附加到列表(字符)中。但是现在我需要一种方法来计算一个字符在该列表中返回的次数,并以频率表示。

【问题讨论】:

  • 为什么你的函数有 2 个return 语句?第二部分永远不会运行...
  • 更好的组织结果的方法可能是使用字典,例如{'a': 5, 'b': 2, 'G': 7, ... }

标签: python list count frequency


【解决方案1】:

没有collections.Counter:

import collections

sentence = "A long sentence may contain repeated letters"

count = collections.defaultdict(int)  # save some time with a dictionary factory
for letter in sentence:  # iterate over each character in the sentence
    count[letter] += 1  # increase count for each of the sentences

或者如果您真的想完全手动完成:

sentence = "A long sentence may contain repeated letters"

count = {}  # a counting dictionary
for letter in sentence:  # iterate over each character in the sentence
    count[letter] = count.get(letter, 0) + 1  # get the current value and increase by 1

在这两种情况下,count 字典将每个不同的字母作为其键,其值将是遇到字母的次数,例如:

print(count["e"])  # 8

如果您想让它不区分大小写,请务必在将其添加到计数时调用letter.lower()

【讨论】:

    【解决方案2】:

    collections 模块中有一个非常方便的函数Counter,它将计算序列中对象的频率:

    import collections
    collections.Counter('A long sentence may contain repeated letters')
    

    这将产生:

    Counter({' ': 6,
             'A': 1,
             'a': 3,
             'c': 2,
             'd': 1,
             'e': 8,
             'g': 1,
             'i': 1,
             'l': 2,
             'm': 1,
             'n': 5,
             'o': 2,
             'p': 1,
             'r': 2,
             's': 2,
             't': 5,
             'y': 1})
    

    在您的情况下,您可能想要连接您的行,例如在传入Counter之前使用''.join(lines)

    如果您想使用原始字典获得类似的结果,您可能需要执行以下操作:

    counts = {}
    for c in my_string:
        counts[c] = counts.get(c, 0) + 1
    

    根据您的 Python 版本,这可能会更慢,但使用 dict.get() 方法返回现有计数或默认值,然后再增加字符串中每个字符的计数。

    【讨论】:

    • “不出所料,这会很多慢” collections.Counter 会慢很多(比如两倍的时间,当然取决于数据),而在 Python 3.x 上 collections.Counter 只会稍微快一点(比如 ~10%)。唯一始终如一的快速方法是使用字典工厂或实际的if letter in count: count[letter] += 1 else: count[letter] = 1 检查(在所有 Python 版本中,这应该是最快的)。
    • 感谢@zwer 检查相对速度 - 我已调整答案以做出更保守的说法。
    【解决方案3】:

    您可以使用集合将文本减少为唯一字符,然后只计算:

    text = ' '.join(lines)  # Create one long string
    # Then create a set of all unique characters in the text
    characters = {char for char in text if char.isalpha()}
    statistics = {}         # Create a dictionary to hold the results
    for char in characters: # Loop through unique characters
        statistics[char] = text.count(char) # and count them
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 2022-12-19
      • 2014-06-19
      • 1970-01-01
      • 2021-12-17
      • 2023-03-30
      相关资源
      最近更新 更多