Python 中字符串中每个字符的频率
pythonserver side programmingprogramming更新于 2025/11/23 22:36:17
文本处理已成为机器学习和人工智能的一个重要领域。Python 通过许多可用的工具和库支持该领域。在本文中,我们将了解如何找到给定字符串中每个字母的出现次数。
使用 Counter
Counter 方法计算可迭代对象中元素的出现次数。因此,只需将所需的字符串传递给它即可直接使用。
示例
from collections import Counter
# 给定字符串
strA = "timeofeffort"
print("Given String: ",strA)
# 使用 counter
res = {}
for keys in strA:
res[keys] = res.get(keys, 0) + 1
# 结果
print("Frequency of each character :\n ",res)
输出
运行上述代码得到以下结果 −
输出
Given String: timeofeffort
Frequency of each character :
{'t': 2, 'i': 1, 'm': 1, 'e': 2, 'o': 2, 'f': 3, 'r': 1}
使用 get()
我们可以将字符串视为字典,并在 for 循环中使用 get() 计算每个字符的键数。
示例
# 给定字符串
strA = "timeofeffort"
print("Given String: ",strA)
# 使用计数器
res = {}
for keys in strA:
res[keys] = res.get(keys, 0) + 1
# 结果
print("Frequency of each character :\n ",res)
输出
运行上述代码得到以下结果 −
Given String: timeofeffort
Frequency of each character :
{'t': 2, 'i': 1, 'm': 1, 'e': 2, 'o': 2, 'f': 3, 'r': 1}
使用 set
python 中的 set 存储唯一元素。因此,我们可以明智地使用它,在将字符串作为可迭代对象循环时,计算一次又一次遇到相同字符的次数。
示例
# 给定字符串
strA = "timeofeffort"
print("Given String: ",strA)
# 使用计数器
res = {}
res={n: strA.count(n) for n in set(strA)}
# 结果
print("Frequency of each character :\n ",res)
输出
运行上述代码得到以下结果 −
Given String: timeofeffort
Frequency of each character :
{'f': 3, 'r': 1, 'm': 1, 'o': 2, 'i': 1, 't': 2, 'e': 2}
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

