我想用下一个单词替换和标记段落中的多个单词。
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]"
希望对你有帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句