【问题标题】:counting the frequency of a letter in a string计算字符串中字母的频率
【发布时间】:2023-03-25 06:37:01
【问题描述】:

到目前为止,这就是我所拥有的,而且这只会打印出一个列表,其中包含字符串中每个字母的计数。它只检查小写字母。

`S="""Four score and seven years ago our fathers brought forth on this continent a new nation
Now we are engaged in a great civil war
"""
lowlet = S.lower()
L_count = [0]*26
total_count = 0
alpha = "abcdefghijklmnopqrstuvwxyz"
i = 0
while i < len(lowlet):
    if lowlet[i] in alpha:
        L_count[i][ord(lowlet[i]) - 97] += 1
        total_count += 1
    i += 1
print('total count of letters:',total_count)'

现在我给出了这个算法,但我不能把它放到代码中,我不能使用 for 循环我必须使用 while 循环 初始化一个列表,L_freq。 对于 L_counts 中的每个元素,count 找到这个计数对应的字母 插入L_freq,列表:[count, letter]

【问题讨论】:

标签: python-3.x


【解决方案1】:

要求它是一个列表吗?我觉得字典会更容易处理

sentence = s.lower()
counts = { letter: sentence.count(letter) for letter in alpha }
print(counts)

这将打印如下: {'a': 5, 'b': 2}

【讨论】:

  • 是的,我认为这是列表中的一个元组。是的,最困难的是字典会更容易。这就是为什么我在所有这些限制方面遇到这么多麻烦。
  • 您考虑过使用collections.Counter吗?
  • 我还没有真正进入那个话题,但我只是查了一下,这似乎是个好主意。
猜你喜欢
  • 2018-09-08
  • 2021-12-31
  • 2012-06-04
  • 2017-04-20
  • 2016-07-25
  • 2019-06-04
  • 2012-10-24
相关资源
最近更新 更多