簡體   English   中英

找到一個沒有被另一個詞接續的詞

[英]Find a word not proceeded by another word

我想知道如何編寫一個正則表達式模式來查找列表中的任何單詞都沒有被另一個單詞處理的字符串:

為了給出上下文,想象兩個單詞列表:

Parts = ['spout', 'handle', 'base']
Objects = ['jar', 'bottle']

想象以下字符串

string = 'Jar with spout and base'
string2 = 'spout of jar'
string3 = 'handle of jar'
string4 = 'base of bottle with one handle' 
string5 = 'bottle base'

我想寫一個規則,這樣如果我們有像“罐子的噴口”或“瓶子的把手”或“瓶底”這樣的表達式,我可以輸出這樣的語句“對象是罐子的碎片,有部分噴口/底座”進入數據幀,但如果我們有一個像“jar with spout”這樣的表達式,我可以輸出一個像“object is jug, has part spout”這樣的表達式。

基本上,我想編寫一個規則,以便如果字符串中存在 Parts 中的任何單詞,我們會寫出該對象是一個片段——除非該單詞以 'with' 開頭。

所以我寫了這個,負向后跟 .* 后跟 Parts 中的任何單詞:

rf"(?!with)(.*)(?:{'|'.join(Part)})"

但這似乎不起作用:當我在 Python 中嘗試時,“帶噴口的罐子”仍將匹配此模式。

所以我只是不知道如何編寫一個正則表達式模式來排除任何涉及“with”后跟任何字符序列,然后是 Parts 中的單詞的表達式

非常感謝可以在這里提供的任何幫助!

您可以輕松地為 PyPi regex庫編寫這樣的模式(使用pip install regex ):

(?<!\bwith\b.*?)\b(?:spout|handle|base)\b

請參閱正則表達式演示 詳情

  • (?<!\\bwith\\b.*?) - 緊靠當前位置的左側,不應該有整個單詞with和除換行符以外的零個或多個字符,盡可能少
  • \\b(?:spout|handle|base)\\b - 一個完整的詞spouthandlebase

請參閱Python 演示

import regex
Parts = ['spout', 'handle', 'base']
Objects = ['jar', 'bottle']
strings = ['Jar with spout and base','spout of jar','handle of jar','base of bottle with one handle','bottle base']
pattern = regex.compile(rf"(?<!\bwith\b.*?)\b(?:{'|'.join(Parts)})\b")
print( list(filter(pattern.search, strings)) )
# => ['spout of jar', 'handle of jar', 'base of bottle with one handle', 'bottle base']

暫無
暫無

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

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