有没有办法删除字符串中重复的和连续的单词短语?

有没有办法删除字符串中重复的和连续的单词短语?,第1张

有没有办法删除字符串中重复的和连续的单词/短语

您可以使用re模块。

>>> s = 'foo foo bar bar'>>> re.sub(r'b(.+)s+1b', r'1', s)'foo bar'>>> s = 'foo bar foo bar foo bar'>>> re.sub(r'b(.+)s+1b', r'1', s)'foo bar foo bar'

如果要匹配任意数量的连续出现:

>>> s = 'foo bar foo bar foo bar'>>> re.sub(r'b(.+)(s+1b)+', r'1', s)'foo bar'

编辑。最后一个示例的附加内容。为此,当短语重复时,您必须调用re.sub。所以:

>>> s = 'this is a sentence sentence sentence this is a sentence where phrases phrases duplicate where phrases duplicate'>>> while re.search(r'b(.+)(s+1b)+', s):...   s = re.sub(r'b(.+)(s+1b)+', r'1', s)...>>> s'this is a sentence where phrases duplicate'


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5648431.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存