如何计算给定子字符串在Python字符串中出现的次数?
例如:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
若要获取子字符串的索引,请参见如何查找子字符串的所有出现?。
如何计算给定子字符串在Python字符串中出现的次数?
例如:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
若要获取子字符串的索引,请参见如何查找子字符串的所有出现?。
当前回答
重叠出现:
def olpcount(string,pattern,case_sensitive=True):
if case_sensitive != True:
string = string.lower()
pattern = pattern.lower()
l = len(pattern)
ct = 0
for c in range(0,len(string)):
if string[c:c+l] == pattern:
ct += 1
return ct
test = 'my maaather lies over the oceaaan'
print test
print olpcount(test,'a')
print olpcount(test,'aa')
print olpcount(test,'aaa')
结果:
my maaather lies over the oceaaan
6
4
2
其他回答
这个问题不是很清楚,但我可以回答你表面上的问题。
一个长度为L个字符的字符串S,其中S[1]是字符串的第一个字符,S[L]是最后一个字符,它有以下子字符串:
空字符串”。这里有一个。 对于从1到L的每一个值A,对于从A到L的每一个值B,字符串S[A]..S[B] (包容)。有L + L-1 + L-2 +…1个字符串,对于a 共0.5*L*(L+1)。 注意,第二项包括S[1]..S[L], 即整个原始字符串S。
所以,在长度为L的字符串中有0.5*L*(L+1) +1个子字符串,在Python中呈现这个表达式,你就有了字符串中出现的子字符串的数量。
string="abc"
mainstr="ncnabckjdjkabcxcxccccxcxcabc"
count=0
for i in range(0,len(mainstr)):
k=0
while(k<len(string)):
if(string[k]==mainstr[i+k]):
k+=1
else:
break
if(k==len(string)):
count+=1;
print(count)
在Python 3中,要查找字符串中子字符串的重叠情况,该算法将执行以下操作:
def count_substring(string,sub_string):
l=len(sub_string)
count=0
for i in range(len(string)-len(sub_string)+1):
if(string[i:i+len(sub_string)] == sub_string ):
count+=1
return count
我亲自检查了这个算法,它是有效的。
目前涉及方法计数的最佳答案并不能真正计算重叠出现的次数,也不关心空子字符串。 例如:
>>> a = 'caatatab'
>>> b = 'ata'
>>> print(a.count(b)) #overlapping
1
>>>print(a.count('')) #empty string
9
如果我们考虑重叠的子字符串,第一个答案应该是2而不是1。 对于第二个答案,如果空子字符串返回0作为asnwer会更好。
下面的代码处理这些事情。
def num_of_patterns(astr,pattern):
astr, pattern = astr.strip(), pattern.strip()
if pattern == '': return 0
ind, count, start_flag = 0,0,0
while True:
try:
if start_flag == 0:
ind = astr.index(pattern)
start_flag = 1
else:
ind += 1 + astr[ind+1:].index(pattern)
count += 1
except:
break
return count
现在当我们运行它时:
>>>num_of_patterns('caatatab', 'ata') #overlapping
2
>>>num_of_patterns('caatatab', '') #empty string
0
>>>num_of_patterns('abcdabcva','ab') #normal
2
my_string = """Strings are amongst the most popular data types in Python.
We can create the strings by enclosing characters in quotes.
Python treats single quotes the same as double quotes."""
Count = my_string.lower().strip("\n").split(" ").count("string")
Count = my_string.lower().strip("\n").split(" ").count("strings")
print("The number of occurance of word String is : " , Count)
print("The number of occurance of word Strings is : " , Count)