gpt4 book ai didi

python - 获取句子中字母的频率

转载 作者:行者123 更新时间:2023-12-01 01:53:58 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

关于python - 获取句子中字母的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50428095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com