Skip to main content
 首页 » 编程设计

python正则表达式选择整个单词

2024年10月24日36dflying

我正在编写一个将拼写错误引入句子的脚本。我正在使用 python re 模块用拼写错误替换原始单词。脚本如下所示:

# replacing original word by error 
pattern = re.compile(r'%s' % original_word)     
replace_by = r'\1' + err 
modified_sentence = re.sub(pattern, replace_by, sentence, count=1) 

但问题是,即使 original_word 是另一个词的一部分,这也会被替换,例如:

如果我有

original_word = 'in' 
err = 'il' 
sentence = 'eating food in' 

它将取代“in”在饮食中的出现,例如:

> 'eatilg food in' 

我正在检查 re documentation但它没有给出任何关于如何包含正则表达式选项的示例,例如:

如果我的模式是:

regex_pattern = '\b%s\b' % original_word 

这将解决问题,因为\b 代表“单词边界”。但这似乎不起作用。

我试图通过以下方式找到解决方法:

pattern = re.compile(r'([^\w])%s' % original_word) 

但这行不通。例如:

original_word = 'to' 
err = 'vo' 
sentence = 'I will go tomorrow to the' 

它将其替换为:

> I will go vomorrow to the  

谢谢,感谢您的帮助

请您参考如下方法:

参见 here有关 python re 模块中单词边界的示例。看起来你很接近,只需要把它们放在一起。以下脚本为您提供所需的输出...

import re 
 
original_word = 'to' 
err = 'vo' 
sentence = 'I will go tomorrow to the' 
 
pattern = re.compile(r'\b%s\b' % re.escape(original_word))  
modified_sentence = re.sub(pattern, err, sentence, count=1) 
 
print modified_sentence 

输出 --> 我明天去 vo the