如何计算给定子字符串在Python字符串中出现的次数?
例如:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
若要获取子字符串的索引,请参见如何查找子字符串的所有出现?。
如何计算给定子字符串在Python字符串中出现的次数?
例如:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
若要获取子字符串的索引,请参见如何查找子字符串的所有出现?。
当前回答
我不确定这是否已经被研究过了,但我认为这是一个“一次性”单词的解决方案:
for i in xrange(len(word)):
if word[:len(term)] == term:
count += 1
word = word[1:]
print count
单词是你要搜索的词,术语是你要找的词
其他回答
在给定字符串中查找重叠子字符串的最佳方法是使用正则表达式。使用ahead,它将使用正则表达式库的findall()找到所有重叠的匹配。这里,左边是子字符串,右边是要匹配的字符串。
>>> len(re.findall(r'(?=aa)', 'caaaab'))
3
对于一个有空格分隔的简单字符串,使用Dict会非常快,请参阅下面的代码
def getStringCount(mnstr:str, sbstr:str='')->int:
""" Assumes two inputs string giving the string and
substring to look for number of occurances
Returns the number of occurances of a given string
"""
x = dict()
x[sbstr] = 0
sbstr = sbstr.strip()
for st in mnstr.split(' '):
if st not in [sbstr]:
continue
try:
x[st]+=1
except KeyError:
x[st] = 1
return x[sbstr]
s = 'foo bar foo test one two three foo bar'
getStringCount(s,'foo')
对于重叠计数,我们可以使用use:
def count_substring(string, sub_string):
count=0
beg=0
while(string.find(sub_string,beg)!=-1) :
count=count+1
beg=string.find(sub_string,beg)
beg=beg+1
return count
对于非重叠的情况,我们可以使用count()函数:
string.count(sub_string)
#counting occurence of a substring in another string (overlapping/non overlapping)
s = input('enter the main string: ')# e.g. 'bobazcbobobegbobobgbobobhaklpbobawanbobobobob'
p=input('enter the substring: ')# e.g. 'bob'
counter=0
c=0
for i in range(len(s)-len(p)+1):
for j in range(len(p)):
if s[i+j]==p[j]:
if c<len(p):
c=c+1
if c==len(p):
counter+=1
c=0
break
continue
else:
break
print('number of occurences of the substring in the main string is: ',counter)
场景1:句子中出现一个单词。 str1 =“这是一个例子,很简单”。单词“is”的出现。让str2 = "is"
count = str1.count(str2)
场景二:句子中出现句式。
string = "ABCDCDC"
substring = "CDC"
def count_substring(string,sub_string):
len1 = len(string)
len2 = len(sub_string)
j =0
counter = 0
while(j < len1):
if(string[j] == sub_string[0]):
if(string[j:j+len2] == sub_string):
counter += 1
j += 1
return counter
谢谢!