我正在尝试编写一个代码,在这里我可以输入一个随机的句子,并计算一个字母在这个字符串中返回的次数:
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
到目前为止,我已经实现了将输入的每个字母附加到列表(chars)中。但是现在我需要一种方法来计算一个字符在列表中返回的次数,并用一个频率来表示。在
没有
collections.Counter
:或者如果您真的想完全手动执行:
^{pr2}$在这两种情况下,
^{3}$count
字典将以每个不同的字母作为其键,其值将是遇到一个字母的次数,例如:如果您希望它不区分大小写,请确保在将其添加到计数时调用
letter.lower()
。在在} ,它将计算序列中对象的频率:
collections
模块中有一个非常方便的函数^{将产生:
^{pr2}$在您的例子中,您可能需要连接您的行,例如在传递到
Counter
之前使用''.join(lines)
。在如果要使用原始词典获得类似的结果,可能需要执行以下操作:
^{3}$根据您的Python版本,这可能会比较慢,但是在增加字符串中每个字符的计数之前,使用
.get()
方法dict
返回现有计数或默认值。在您可以使用集合将文本缩减为唯一字符,然后只计算:
相关问题 更多 >
编程相关推荐