如何计算给定子字符串在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

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

其他回答

如果你想数整个字符串,这是可行的。

stri_count="If you're looking to count the whole string this can works"
print(len(stri_count))
def count_substring(string, sub_string):
    k=len(string)
    m=len(sub_string)
    i=0
    l=0
    count=0
    while l<k:
        if string[l:l+m]==sub_string:
            count=count+1
        l=l+1
    return count

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()

    count = count_substring(string, sub_string)
    print(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

重叠出现:

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

你可以用两种方法计算频率:

使用str中的count(): a.count (b) 或者,你可以用: len (a.split (b)) 1

其中a是字符串,b是要计算频率的子字符串。