如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
当前回答
最简单的方法是一行代码:
'Mary had a little lamb'.count("a")
但是如果你想用这个也可以:
sentence ='Mary had a little lamb'
count=0;
for letter in sentence :
if letter=="a":
count+=1
print (count)
其他回答
这个简单直接的函数可能会有帮助:
def check_freq(x):
freq = {}
for c in set(x):
freq[c] = x.count(c)
return freq
check_freq("abbabcbdbabdbdbabababcbcbab")
{'a': 7, 'b': 14, 'c': 3, 'd': 3}
如果需要理解:
def check_freq(x):
return {c: x.count(c) for c in set(x)}
我知道要求是数一个特定的字母。我在这里没有使用任何方法编写泛型代码。
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
python - 3. x:
"aabc".count("a")
Str.count (sub[, start[, end]]) 返回子字符串sub在范围[start, end]中不重叠出现的次数。可选参数start和end被解释为片表示法。
正则表达式?
import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))
我是pandas库的粉丝,尤其是value_counts()方法。你可以用它来计算字符串中每个字符的出现次数:
>>> import pandas as pd
>>> phrase = "I love the pandas library and its `value_counts()` method"
>>> pd.Series(list(phrase)).value_counts()
8
a 5
e 4
t 4
o 3
n 3
s 3
d 3
l 3
u 2
i 2
r 2
v 2
` 2
h 2
p 1
b 1
I 1
m 1
( 1
y 1
_ 1
) 1
c 1
dtype: int64