【发布时间】:2012-09-14 07:50:24
【问题描述】:
我想替换字符串句子中的单词,例如:
What $noun$ is $verb$?
用实际的名词/动词替换'$ $'(包括)中的字符的正则表达式是什么?
【问题讨论】:
我想替换字符串句子中的单词,例如:
What $noun$ is $verb$?
用实际的名词/动词替换'$ $'(包括)中的字符的正则表达式是什么?
【问题讨论】:
您不需要正则表达式。我会做的
string = "What $noun$ is $verb$?"
print string.replace("$noun$", "the heck")
仅在需要时使用正则表达式。它通常较慢。
【讨论】:
str.replace("$noun$", noun).replace("$verb$", verb)
types[word]。
鉴于您可以根据自己的喜好随意修改$noun$ 等,现在最好的做法可能是在字符串上使用format 函数:
"What {noun} is {verb}?".format(noun="XXX", verb="YYY")
【讨论】:
In [1]: import re
In [2]: re.sub('\$noun\$', 'the heck', 'What $noun$ is $verb$?')
Out[2]: 'What the heck is $verb$?'
【讨论】:
使用字典来保存正则表达式模式和值。使用 re.sub 替换标记。
dict = {
"(\$noun\$)" : "ABC",
"(\$verb\$)": "DEF"
}
new_str=str
for key,value in dict.items():
new_str=(re.sub(key, value, new_str))
print(new_str)
输出:
What ABC is DEF?
【讨论】: