如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
当前回答
正则表达式?
import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))
其他回答
myString.count('a');
更多信息请点击这里
不超过这个IMHO -你可以添加上或下的方法
def count_letter_in_str(string,letter):
return string.count(letter)
我知道要求是数一个特定的字母。我在这里没有使用任何方法编写泛型代码。
sentence1 =" Mary had a little lamb"
count = {}
for i in sentence1:
if i in count:
count[i.lower()] = count[i.lower()] + 1
else:
count[i.lower()] = 1
print(count)
输出
{' ': 5, 'm': 2, 'a': 4, 'r': 1, 'y': 1, 'h': 1, 'd': 1, 'l': 3, 'i': 1, 't': 2, 'e': 1, 'b': 1}
现在如果你想要任何特定的字母频率,你可以像下面这样打印。
print(count['m'])
2
要查找句子中字符的出现情况,您可以使用下面的代码
首先,我从句子中取出了唯一的字符,然后我计算了每个字符在句子中的出现次数,其中包括空格的出现次数。
ab = set("Mary had a little lamb")
test_str = "Mary had a little lamb"
for i in ab:
counter = test_str.count(i)
if i == ' ':
i = 'Space'
print(counter, i)
以上代码的输出如下所示。
1 : r ,
1 : h ,
1 : e ,
1 : M ,
4 : a ,
1 : b ,
1 : d ,
2 : t ,
3 : l ,
1 : i ,
4 : Space ,
1 : y ,
1 : m ,
不使用Counter(), count和regex获得所有字符计数的另一种方法
counts_dict = {}
for c in list(sentence):
if c not in counts_dict:
counts_dict[c] = 0
counts_dict[c] += 1
for key, value in counts_dict.items():
print(key, value)