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

use*_*130 -1 python string duplicates

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

Tim*_*sen 8

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

inp = 'Hey there There'
output = re.sub(r'(\w+) \1', r'\1', inp, flags=re.IGNORECASE)
print(output)  # Hey there
Run Code Online (Sandbox Code Playgroud)

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

inp = 'Hey there There'
output = re.sub(r'(\w+) \1', r'\1', inp, flags=re.IGNORECASE)
print(output)  # Hey there
Run Code Online (Sandbox Code Playgroud)

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