簡體   English   中英

Python 正則表達式 findall 匹配所有單詞對

[英]Python regex findall matching all pairs of words

我需要使用正則表達式在字符串中按順序列出每對單詞,代碼的相關部分是這樣的:

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

現在讓我們以文本“這是一個隨機文本”為例,我想要的是這樣的列表:

['這是','是一個','一個隨機','隨機文本']

相反,我得到的是:

['這是','隨機']

我怎樣才能解決這個問題? 提前致謝。

您說單詞由隨機數量的空格和/或標點符號分隔,我為此使用了[\s\.]+

你在這里做錯的是你正在消費第二個單詞,你需要的是一個匹配第二個單詞但不消費它的積極前瞻,所以下次它會匹配它。 因為你說這是一個巨大的文本,我認為使用finditerfindall更好,不同之處在於它返回一個生成器,該生成器產生與findall返回的相同元素:

import re

text ="""This. is a random text"""

pattern = re.compile(r'(\w+[\s\.]+)(?=(\w+))')
for match in pattern.finditer(text):
    # rebuild the word
    element = ''.join(match.groups())
    print(element)

輸出:

This. is
is a
a random
random text

請注意,默認情況下,正向前瞻不是捕獲組,這就是為什么我這樣做(?=(\w+))來捕獲其中的單詞。 第一組是(\w+[\s\.]+) 我用join再次重建連接組。

如果您想為此任務使用正則表達式,請查看以下內容:

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

正則表達式演示

訣竅是對第二個單詞使用積極的前瞻並在一個組中捕獲它。 為了得到 output 結果對,組合第 1 組和第 2 組匹配的結果。

通常我不認為同一個 RegEx 允許重疊的搜索結果。 相反,您可能想要做的是找到中間空格並找到空格之前和之后的單詞。

在這種情況下,您不需要使用正則表達式,您可以使用 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}"


但是你真的需要正則表達式嗎? 你可以在沒有正則表達式的情況下做到這一點

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']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM