Python regex findall匹配所有成对的单词

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

我需要使用正则表达式在字符串中按顺序列出每对单词的列表,代码的相关部分是这样的:

for word in re.findall(r'\w+\b.*?\w+', text):

现在让我们以文本“这是一个随机文本”为例,我想要的是这样的列表:

['这是','是一个','一个随机','随机文本']

相反,我得到的是这个:

['这是','一个随机']

我该如何解决?预先感谢。

python regex python-3.x
4个回答
0
投票

通常,我不认为同一个RegEx允许重叠的搜索结果。您可能想要做的是找到中间空格,并找到该空格之前和之后的单词。


0
投票

如果您想使用正则表达式来执行此任务,请看一下:

(\w+)\s+(?=(\w+))

Regex Demo

窍门是对第二个单词使用positive lookahead并将其捕获到一个组中。为了输出结果对,请组合组1和组2的匹配结果。


0
投票

在这种情况下,您无需使用正则表达式,只需使用split

st = "This is a random text"
sp = st.split()

result = [f"{w1} {w2}" for w1, w2 in zip(sp, sp[1:])]
print(result)

结果

['This is', 'is a', 'a random', 'random text']

编辑

对于大数据,您可以实现生成器。像下面的伪代码

def get_pair_from_large_text():
    tail_of_last_chunk = ""
    while True
        chunk = get_string_chunk_from_source()
        if len(chunk)==0:
            yield f"{words[-2]} {words[-1]}"
            break
        chunk = tail_of_last_chunk[1] + chunk

        words = split(chunk)
        tail_of_last_chunk = words[-2], words[-1]

        for w1, w2 in zip(words[:-1], words[1:-1])
            yield f"{w1} {w2}"



0
投票

但是您真的需要正则表达式吗?你可以不用正则表达式就可以做到

L1 = line.split(' ')
L2 = L1[1:].append(' ')
Result = [' '.join(a,b) for a,b in zip(L1,L2)]

使用正则表达式,但结果不正确

>>> pattern1 = re.compile(r"(\w+\s+\w+)")
>>> pattern2 = re.compile(r"(\s+\w+\s+\w+)")
>>> l1 = re.findall(pattern1, line)
>>> l2 =[x.strip() for x in re.findall(pattern2, line)]
>>> l1
['This is', 'a random']
>>> l2
['is a', 'random text']
>>> l1 + l2
['This is', 'a random', 'is a', 'random text']
© www.soinside.com 2019 - 2024. All rights reserved.