python - 用python计算字母

标签 python string

我想做的是计算每个字母在字符串中出现的次数。我想将详细信息存储在字典中。
以下是我的尝试:

def scan(string):
    list_string = []
    for letter in string:
         list_string.append(letter)

    list_string.sort()
    scanned = {}

    for k in range(0,len(list_string)):
        count = 0
        for kk in range(k,len(list_string)):
            if list_string[k] == list_string[kk]:
                count += 1

        scanned.update({list_string[k]:count})

    return scanned

然而,即使一个字母有时出现不止一次,每个键的值都是 1。

当我尝试这个时它工作正常

print("Letter '{}': \t {}.format(list_string[k],count)) 

有人能帮忙吗?

最佳答案

from collections import Counter

letter_count = Counter(mystring)

关于python - 用python计算字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44606541/

相关文章:

Python pysqlite2 dbapi2问题

python - if __name__ == '__main__' 的风格指南是什么?

C Pointers & Memory - 写了一段代码...抛出异常

javascript - React 在渲染之前为字符串的特定部分提供样式?

c - 如何定义和初始化结构体内部的字符串数组?

python - 子图边距以适合 matplotlib 中的标题和标签

python - 在 Pandas 中检查具有相同条件的多列的更好方法?

c++ - std::String 调整大小不改变地址

c - 如何检查字符串是否存在于字符数组的数组中

python - 在 Python 中使用 Microsoft.Office.Interop.Excel 和 CLR 打印 Excel 文件?