我需要在文本字符串中查找重复项。 我已经找到了一个非常好的优雅解决方案 here来自@Tim Pietzcker
我对现有的解决方案很满意,但想知道是否可以进一步扩展它,使其接受带有空格的字符串。
例如 "a bcab c"
将返回 [(abc,2)]
我尝试使用正则表达式模式 "([^\s]+?)\1+")
但没有成功。
非常感谢任何帮助。
最佳答案
您应该首先考虑从文本中删除“”。您可以通过正则表达式本身来完成。
>>> def repetitions(s):
... r = re.compile(r"(.+?)\1+")
... for match in r.finditer(re.sub(r'\s+',"",s)):
... yield (match.group(1), len(match.group(0))/len(match.group(1)))
...
输出。
>>> list(repetitions("a bcab c"))
[('abc', 2)]
如果您仍想保留原始文本中的空格,请尝试使用此正则表达式:r"(\s*\S+\s*?\S*?)\1+"
。但这有局限性。
>>> def repetitions(s):
... r = re.compile(r"(\s*\S+\s*?\S*?)\1+")
... for match in r.finditer(s):
... yield (match.group(1), len(match.group(0))/len(match.group(1)))
...
结果:
>>> list(repetitions(" abc abc "))
[(' abc', 2)]
>>> list(repetitions("abc abc "))
[('abc ', 2)]
>>> list(repetitions(" ab c ab c "))
[(' ab c', 2)]
>>> list(repetitions("ab cab c "))
[('ab c', 2)]
>>> list(repetitions("blablabla"))
[('bla', 3)]
关于Python : Regex, 在字符串上查找重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55272367/