gpt4 book ai didi

python - 找到一个没有跟随另一个词的词

转载 作者:行者123 更新时间:2023-12-04 03:55:09 26 4
gpt4 key购买 nike

我想知道如何编写一个正则表达式模式来查找列表中任何单词后面没有另一个单词的字符串:

为了给出上下文,想象两个单词列表:

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 spout”或“handle of bottle”或“bottle base”这样的表达式,我可以输出一个像“object is fragment of jar, has part spout”这样的语句/base”到数据框中,但是如果我们有一个像“带喷口的 jar ”这样的表达式,我可以输出一个像“对象是 jar ,有部分喷口”这样的表达式。

基本上,我想写一个规则,如果 Parts 中的任何单词出现在字符串中,我们就写该对象是一个片段——除非该单词前面有“with”。

所以我写了这个,负向回顾后跟 .* 后跟 Parts 中的任何单词:

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

但这似乎行不通:当我在 Python 中尝试时,“jar with spout”仍将匹配此模式。

所以我只是不确定如何编写正则表达式模式来排除任何涉及“with”的表达式,后跟任何字符序列,后跟部分中的单词

非常感谢这里可以提供的任何帮助!

最佳答案

您可以轻松地为 PyPi 编写这样的模式 regex库(使用 pip install regex 安装):

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

参见 regex demo . 详细信息:

  • (?<!\bwith\b.*?) - 在当前位置的左侧,不应有完整的单词 with以及除换行符以外的任何零个或多个字符,尽可能少
  • \b(?:spout|handle|base)\b - 一个完整的词spout , handle , 或 base .

参见 Python demo :

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

关于python - 找到一个没有跟随另一个词的词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64052973/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com