如何在python中查找段落中的多个单词并将其替换为已识别的下一个单词?

如何在python中查找段落中的多个单词并将其替换为已识别的下一个单词?,python,string,replace,Python,String,Replace,我想用下一个单词替换并标记段落中的多个单词 paragraph = "Python is the most powerful language [YES] yes. my sex is [NO] male [YES] female" 我想用下一个单词替换键[YES]和[NO],如下所示 paragraph = "Python is the most powerful language [YES]yes[/YES]. my sex is [NO]male[/NO] [YES]female[/YE

我想用下一个单词替换并标记段落中的多个单词

paragraph = "Python is the most powerful language [YES] yes. my sex is [NO] male [YES] female"
我想用下一个单词替换键[YES]和[NO],如下所示

paragraph = "Python is the most powerful language [YES]yes[/YES]. my sex is [NO]male[/NO] [YES]female[/YES]"

您可以使用正则表达式来实现以下结果:
代码如下:

import re

paragraph = "Python is the most powerful language [YES] yes. my sex is [NO] male [YES] female"

paragraph = re.sub(r"\[(.*?)\]\s\b(\w+)\b", r"[\1]\2[/\1]", paragraph)
输出为:

"Python is the most powerful language [YES]yes[/YES]. my sex is [NO]male[/NO] [YES]female[/YES]"

希望它能帮助你

你能告诉我们你为什么要这么做吗。可能有一种更简单的方法,实际上我正在处理包含复选框的扫描pdf。在目标检测和ocr之后,我将得到这样一个段落,复选框将替换为[YES]和[NO]键。我只想用下一个单词替换这个键。你可以使用正则表达式。搜索“[YES]”,后跟空格,然后是一组字符,以空格结尾。S+将匹配任何非空格的内容。
"Python is the most powerful language [YES]yes[/YES]. my sex is [NO]male[/NO] [YES]female[/YES]"