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

后端 未结 4 1443
栀梦
栀梦 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: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.

提交回复
热议问题