我正在尝试编写一个正则表达式来捕获特定的单词replace I

2024-09-26 21:41:59 发布

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

我有以下声明

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.

我想用“代词”替换所有的“my”,如下所示。我不想取代我自己,我想保持现状

预期输出为:

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$')

Tags: toinfriendismysomehibut
1条回答
网友
1楼 · 发布于 2024-09-26 21:41:59

你很接近。在起点和终点使用边界。你知道吗

例如:

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.

相关问题 更多 >

    热门问题