我正在尝试写一条以捕获特定单词替换的正则态度



我有以下语句,

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

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

您非常接近。在开始和结束时使用边界。

ex:

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'bmyb', "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.

最新更新