Skip to main content
 首页 » 编程设计

python之如何查找/替换独立的单词或带有某些形容词的单词

2024年10月25日10jackei

German apple is good. Apple is nice. Where is the apple? English apple have worms. English people are nice.

如果我有上面的示例,我想用 German apple 替换所有出现的 Apple 或 apple。在上面的示例中,German apple 应该被忽略,因为它已经是正确的。只有一个异常(exception),如果有 English apple 那么它仍然应该被替换为 German apple

在线使用regex generators ,我想到了这个:

似乎以下允许我选择所有苹果(全局,多行) 但这也选择了 German apple,这是我应该禁止的。

/\b(apple)/igm 

这种尝试也没有真正奏效。它只选择 apple?。

/\b(apple)[^German apple]/igm 

我已经卡在这里了。将不胜感激。

更新:

如解释的那样,我正在查看正面和负面的环视 here .

如果我在上面的示例中添加了另一行:

Apple from Dutch is sour.

我想说忽略Apple from Dutch,就像我们对German apple 所做的那样。 如何实现?

我试过了,但运气不好:

(?i)(?:English )?(?:(?<!German )\bapple\b(?<! from dutch)) 

请您参考如下方法:

使用下面的正则表达式,然后将匹配项替换为 German apple

(?<!German )(?:English )?\bapple\b 

DEMO

或

(?i)(?:English )?(?:(?<!German )\bapple\b) 
  • (?i)不区分大小写的修饰符。
  • (?:English )?匹配可选的 English字符串。
  • (?:(?<!German )\bapple\b)匹配所有 apple仅当其前面没有 German 时才为字符串. (?<!German ) negative lookbehind 断言我们要匹配的字符串前面不会出现与负 lookbehind 中存在的模式匹配的字符串。

DEMO

例子:

>>> string = 'German apple is good. Apple is nice. Where is the apple? English apple have worms. English people are nice.' 
>>> re.sub(r'(?i)(?:English )?(?:(?<!German )\bapple\b)', r'German apple', string) 
'German apple is good. German apple is nice. Where is the German apple? German apple have worms. English people are nice.' 

更新:

(?i)(?:English )?(?:(?<!German )\bapple\b)(?!\s+from\s+Dutch\b) 

DEMO