簡體   English   中英

如何在數據丟失的情況下保持ReqEX輸出的長度穩定,python2.7

[英]how to keep length of ReqEX output stable in case of missing data, python2.7

以下regExp將匹配前后3個單詞( 如果存在)

((?:\w+\s+){0,3}My_WORD_HERE(?:\s+\w+){0,3})

輸出將是這樣的:

word1 word2 word3 My_WORD_HERE word1 word2 word3

要么

word1 word2 My_WORD_HERE word1導致空屬性。

如何用“?”等值填充缺失的單詞? 還是任何符號?

輸出就像這樣

word1 word2 ? My_WORD_HERE word1 ? ?

我將把這個輸出用於Weka ML

非常感謝大家

您可以使用lambda執行替換:

import re

s = 'word1 word2 My_WORD_HERE word1'
word = 'My_WORD_HERE'
wnb = 3

pat = r'((?:\w+\s+){{0,{0}}}){1}((?:\s+\w+){{0,{0}}})'.format(wnb, word)

res = re.sub(pat, lambda m:
    m.group(1) +
    '? '*(wnb-len(m.group(1).split())) +
    word + m.group(2) +
    ' ?'*(wnb-len(m.group(2).split())), s)

不是純正的正則表達式替換解決方案,但應該做的伎倆:

import re

def replaceMissingWords(text, word, placeholder):
    match = re.match(r'(\w+)?\s*(\w+)?\s*(\w+)?({0})\s*(\w+)?\s*(\w+)?\s*(\w+)?$'.format(word), text)
    if match is None:
        return text
    return ' '.join(list(map(lambda x: x is None and placeholder or x, match.groups())))

print(replaceMissingWords('word1 word2 My_WORD_HERE word1', 'My_WORD_HERE', '?'))
// output: 'word1 word2 ? My_WORD_HERE word1 ? ?'

AFAIK python正則表達式引擎不支持在堆棧上存儲多個捕獲的組,因此我們必須在之前和之后手動列出捕獲組。

在這里演示

暫無
暫無

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

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