Skip to main content
 首页 » 编程设计

python之我正在尝试编写一个正则表达式来捕获特定的单词替换它

2025年05月04日22freeliver54

我有以下声明,

sentence = " Hi my goal is to achieve highest score in mathematics, but my friend has scored some how more. and now i am myself depressed. 

我想将所有“我的”替换为“代词”,如下所示。我不想取代我自己,我想保持原样

预期输出是:

Hi PRONOUN goal is to achieve highest score in mathematics, but PRONOUN friend has scored some how more. and now i am myself depressed. 

我试过在 python 中使用正则表达式

 regex = re.sub(r'\\bmy$') 

请您参考如下方法:

你们很亲近。在起点和终点使用边界。

例如:

import re 
 
sentence = "Hi my goal is to achieve highest score in mathematics, but my friend has scored some how more. and now i am myself depressed." 
print(re.sub(r'\bmy\b', "PRONOUN", sentence)) 

输出:

Hi PRONOUN goal is to achieve highest score in mathematics, but PRONOUN friend has scored some how more. and now i am myself depressed.