Regex使用AND NOT op

2024-09-28 19:06:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一个正则表达式,我在文本中找到,单词“ata de audiência”或“termo de audiência”,找到“incocilia”、“reclamante”和“reclamada”,没有找到单词“sentença”

if(re.search(r'ata de audiência' or r'termo de audiência') and r'inconcilia' and r'reclamada' and r'reclamante' and not r'sentença', content.read())):
            key_content = True

我试着这样做。。我可以找到单词,但是当我使用“AND NOT”操作符时,正则表达式不起作用

附言:有葡萄牙语单词


Tags: and文本reifdecontent单词audi
3条回答

问题中的代码不够完整,无法详细注释,但第一个问题是误解了传递给re.search()的参数。你知道吗

以下代码是布尔表达式:

r'ata de audiência' or r'termo de audiência'

Python将其解释为“使用第一个字符串,如果不是无或非空,则使用第二个”。你知道吗

在控制台上:

>>> r'ata de audiência' or r'termo de audiência'
'ata de audiência'

andnot类似:

>>> r'inconcilia' and r'reclamada'
'reclamada'

>>> r'inconcilia' and r'reclamada' and r'reclamante' and not r'sentença'
False

您需要提供一个独立的小示例。通常情况下,准备这个例子会让你有很长的路来回答这个问题。你知道吗

你不需要正则表达式。你知道吗

text = content.read()

if ('ata de audiência' in text or 'termo de audiência' in text) \
    and 'inconcilia' in text and 'reclamada' in text \
    and 'reclamante' in text and not 'sentença' in text:
        key_content = True

正则表达式不是这样工作的。如果你真的想用的话,我建议你多看看。你知道吗

对于您的需要,in关键字更合适。如果子字符串在字符串中,则返回True;如果子字符串不在字符串中,则返回False。可以使用andor命令链接这些子字符串,也可以执行以下操作:

contents_text = content.read()
if any(word in contents_text for word in ['ata de audiência', 'termo de audiência']) 
    and all(word in context_text for word in ['inconcilia', 'reclamada', 'reclamante'])
    and 'sentença' not in context_text:
        key_content = True

相关问题 更多 >