使用Python删除字符串中相邻的重复单词?

我将如何删除字符串中相邻的重复单词。例如“嘿那里”->“嘿那里”

回答

使用re.sub反向引用,我们可以尝试:

inp = 'Hey there There'
output = re.sub(r'(w+) 1', r'1', inp, flags=re.IGNORECASE)
print(output)  # Hey there
inp = 'Hey there There'
output = re.sub(r'(w+) 1', r'1', inp, flags=re.IGNORECASE)
print(output)  # Hey there

此处使用的正则表达式模式表示:

然后,我们只用第一个相邻的单词替换。


以上是使用Python删除字符串中相邻的重复单词?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>