如何计算给定子字符串在Python字符串中出现的次数?

例如:

>>> 'foo bar foo'.numberOfOccurrences('foo')
2

若要获取子字符串的索引,请参见如何查找子字符串的所有出现?。


当前回答

对于一个有空格分隔的简单字符串,使用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')

其他回答

这个问题不是很清楚,但我可以回答你表面上的问题。

一个长度为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中呈现这个表达式,你就有了字符串中出现的子字符串的数量。

这里有一个解决方案,适用于非重叠和重叠的情况。为了澄清:重叠子字符串是指其最后一个字符与其第一个字符相同的子字符串。

def substr_count(st, sub):
    # If a non-overlapping substring then just
    # use the standard string `count` method
    # to count the substring occurences
    if sub[0] != sub[-1]:
        return st.count(sub)

    # Otherwise, create a copy of the source string,
    # and starting from the index of the first occurence
    # of the substring, adjust the source string to start
    # from subsequent occurences of the substring and keep
    # keep count of these occurences
    _st = st[::]
    start = _st.index(sub)
    cnt = 0

    while start is not None:
        cnt += 1
        try:
            _st = _st[start + len(sub) - 1:]
            start = _st.index(sub)
        except (ValueError, IndexError):
            return cnt

    return cnt

如果你正在寻找一个适用于所有情况的幂解,这个函数应该工作:

def count_substring(string, sub_string):
    ans = 0
    for i in range(len(string)-(len(sub_string)-1)):
        if sub_string == string[i:len(sub_string)+i]:
            ans += 1
    return ans

我不确定这是否已经被研究过了,但我认为这是一个“一次性”单词的解决方案:

for i in xrange(len(word)):
if word[:len(term)] == term:
    count += 1
word = word[1:]

print count

单词是你要搜索的词,术语是你要找的词

s = input('enter the main string: ')
p=input('enter the substring: ')
l=[]
for i in range(len(s)):
    l.append(s[i:i+len(p)])
print(l.count(p))