从字符串返回重复的单词

问题描述 投票:0回答:1

我有一个字符串:“你还好吗?[你好,你好,你好]。是的,我是![再见,再见]”

我需要在列表中返回['Hello Hello Hello,'Bye Bye Bye']。

使用正则表达式应该是最简单的。我已经尝试过findall(),但是它只返回第一个单词,例如Hello和Bye,而不返回[Hello Hello Hello]或[Bye Bye Bye]的整个字符串。我也尝试过finditer(),但这也正在返回唯一的第一世界。

text = "Are you ok? [Hello Hello Hello]. Yes I am! [Bye Bye Bye]"
def find_words(text):
    p = re.compile(r'(\w{3,})\s\1')
    for match in p.finditer(text):
        print(match.groups(0))

预期结果['Hello Hello Hello','Bye Bye Bye']当我运行代码时,我得到['Hello','Bye']

python
1个回答
0
投票

您可以尝试使用此正则表达式吗?

\b(\w+)\s+\1\b

从这里Regular Expression For Consecutive Duplicate Words

© www.soinside.com 2019 - 2024. All rights reserved.