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

2024-05-29 07:23:16 发布

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

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

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]"

Tags: theno标记mostismy单词language
2条回答
paragraph = "Python is the most powerful language [YES] yes. my sex is [NO] male [YES] female"

def find_replace(paragraph):
    par = paragraph.split(" ")
    for i, p in enumerate(par):
        if p == "[NO]":
            par[i] = "[NO]" + par[i+1] + "[/NO]"
            del par[i+1]

    # the same for [YES]

    return " ".join(par)

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

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]"

希望它能帮助你

相关问题 更多 >

    热门问题