如何计算字符串中字符出现的次数?

如。“a”在“Mary had a little lamb”中出现了4次。


当前回答

正则表达式?

import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))

其他回答

要获得所有字母的计数,请使用集合。计数器:

>>> from collections import Counter
>>> counter = Counter("Mary had a little lamb")
>>> counter['a']
4

拿起这个用户的评论:

import numpy as np
sample = 'samplestring'
np.unique(list(sample), return_counts=True)

Out:

(array(['a', 'e', 'g', 'i', 'l', 'm', 'n', 'p', 'r', 's', 't'], dtype='<U1'),
 array([1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1]))

检查“年代”。可以通过如下方式过滤两个数组的元组:

a[1][a[0]=='s']

旁注:它的工作原理类似于集合包的Counter(),只是在numpy中,无论如何都要导入numpy。你也可以在单词列表中计算唯一的单词。

正则表达式?

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

这是公认答案的延伸,你应该在文本中寻找所有字符的计数。

# Objective: we will only count for non-empty characters

text = "count a character occurrence"
unique_letters = set(text)
result = dict((x, text.count(x)) for x in unique_letters if x.strip())

print(result)
# {'a': 3, 'c': 6, 'e': 3, 'u': 2, 'n': 2, 't': 2, 'r': 3, 'h': 1, 'o': 2}