如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
当前回答
正则表达式非常有用,如果你想要区分大小写(当然还有regex的所有功能)。
my_string = "Mary had a little lamb"
# simplest solution, using count, is case-sensitive
my_string.count("m") # yields 1
import re
# case-sensitive with regex
len(re.findall("m", my_string))
# three ways to get case insensitivity - all yield 2
len(re.findall("(?i)m", my_string))
len(re.findall("m|M", my_string))
len(re.findall(re.compile("m",re.IGNORECASE), my_string))
请注意,regex版本的运行时间大约是它的十倍,只有当my_string非常长或代码处于深度循环中时,这才可能成为问题。
其他回答
正则表达式?
import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))
拿起这个用户的评论:
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
def count(s, ch):
pass
def main():
s = raw_input ("Enter strings what you like, for example, 'welcome': ")
ch = raw_input ("Enter you want count characters, but best result to find one character: " )
print ( len (re.findall ( ch, s ) ) )
main()
不超过这个IMHO -你可以添加上或下的方法
def count_letter_in_str(string,letter):
return string.count(letter)
这个简单直接的函数可能会有帮助:
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)}