Detect repetitions in string

后端 未结 1 741
梦谈多话
梦谈多话 2020-12-06 04:48

I have a simple problem, but can\'t come with a simple solution :)

Let\'s say I have a string. I want to detect if there is a repetition in it.

I\'d like:

相关标签:
1条回答
  • 2020-12-06 04:53
    import re
    def repetitions(s):
       r = re.compile(r"(.+?)\1+")
       for match in r.finditer(s):
           yield (match.group(1), len(match.group(0))/len(match.group(1)))
    

    finds all non-overlapping repeating matches, using the shortest possible unit of repetition:

    >>> list(repetitions("blablabla"))
    [('bla', 3)]
    >>> list(repetitions("rablabla"))
    [('abl', 2)]
    >>> list(repetitions("aaaaa"))
    [('a', 5)]
    >>> list(repetitions("aaaaablablabla"))
    [('a', 5), ('bla', 3)]
    
    0 讨论(0)
提交回复
热议问题