文本处理已成为机器学习和AI的重要领域。Python通过许多可用的工具和库支持此文件。在本文中,我们将看到如何找到给定字符串中每个字母的出现次数。
Counter方法计算可迭代元素中元素的出现次数。因此,通过将所需的字符串传递到其中来直接使用它。
from collections import Counter
# Given string
strA = "timeofeffort"
print("Given String: ",strA)
# Using counter
res = {}
for keys in strA:
res[keys] = res.get(keys, 0) + 1
# Result
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()我们可以将字符串视为字典,并get()在for循环中使用每个字符计算键值。
# Given string
strA = "timeofeffort"
print("Given String: ",strA)
# Using counter
res = {}
for keys in strA:
res[keys] = res.get(keys, 0) + 1
# Result
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}python中的集合存储唯一元素。因此,我们可以明智地使用它,通过计算一次遍历字符串时,一次又一次遇到相同字符的次数来明智地使用它。
# Given string
strA = "timeofeffort"
print("Given String: ",strA)
# Using counter
res = {}
res={n: strA.count(n) for n in set(strA)}
# Result
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}