How to count all occurrences of a word in a string using python

后端 未结 4 1444
栀梦
栀梦 2021-01-21 04:04

I\'m trying to find the number of times \'bob\' occurs in a string of characters like \'abdebobdfhbobob\'.

My code (that I found through another stackoverflow question)

相关标签:
4条回答
  • 2021-01-21 04:23

    We can just check all possible candidates:

    def count_substrings(sub, main):
        n = len(sub)
        return sum(sub == main[i : i+n] for i in range(len(main) - n + 1))
    
    s = 'abdebobdfhbobob'
    sub = 'bob'
    print('The number of times %s occurs is: %d' % (sub, count_substrings(sub, s)))  # 3
    
    0 讨论(0)
  • 2021-01-21 04:26

    If you don't want to use regular expressions you can create all triplets from the string using zip and then use list.count:

    >>> word = 'bob'
    >>> triplets = (''.join(k) for k in zip(*[s[i:] for i in range(len(word))]))
    >>> triplets.count(word)
    3
    

    The triplets are created by zipping these strings:

         ▼     ▼ ▼
    'abdebobdfhbobob'
    'bdebobdfhbobob'
    'debobdfhbobob'
         ▲     ▲ ▲
    

    If you don't mind working with tuples:

    >>> word = 'bob'
    >>> triplets = zip(*[s[i:] for i in range(len(word))])
    >>> triplets.count(tuple(word))
    3
    

    Tip: If you're going to count other words as well, use a collections.Counter.

    0 讨论(0)
  • 2021-01-21 04:48

    Based on documentation, str.count() return the number of non-overlapping occurrences of substring sub in the range [start, end]. You can use a positive lookahead based regular expression in order to find the overlapped strings:

    >>> import re
    >>> s = 'abdebobdfhbobob'
    >>> len(re.findall(r'(?=bob)', s))
    3
    

    If you don't want to use regex you can use a generator expression within the sum() function that will iterate over the all sub-strings with length 3 and count the number of those that are equal to 'bob':

    >>> sum(s[i:i+3] == 'bob' for i in range(len(s)-2))
    3
    
    0 讨论(0)
  • 2021-01-21 04:48

    why do not you make it easy?

    bobc=0
    for i in range (0,len(s)-2):
        if s[i:i+3]=='bob':
            bobc+=1
            i=+1
    print('Number of bob:'+str(bobc))
    
    0 讨论(0)
提交回复
热议问题