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

标签 python regex

我有以下声明,

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.

关于python - 我正在尝试编写一个正则表达式来捕获特定的单词替换它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55966466/

相关文章:

css - 驼峰式 BEM 的正则表达式

python - boost::python:如何覆盖静态属性?

python - Rabbitmq hello world 连接仅适用于本地主机(python)

javascript - 用 3 种模式替换字符串 "space", "and", "or"

Java转义转义序列

javascript - 如何删除所有非字母字符,javascript

python - 通过使用 pandas 对列进行分组来汇总数据框

python - 使用 OS 命令连接 CSV 文件

python - Python中的Pyo:未定义名称 'Server'

正则表达式 匹配两个字符串之间的所有字符