import re
rep = {"condition1": "", "condition2": "text"} # define desired replacements here
# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
#Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest versions
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
例如:
>>> pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")
'() and --text--'
s = "The quick brown fox jumps over the lazy dog"
for r in (("brown", "red"), ("lazy", "quick")):
s = s.replace(*r)
#output will be: The quick red fox jumps over the quick dog
d = { "cat": "dog", "dog": "pig"}
my_sentence = "This is my cat and this is my dog."
replace_all(my_sentence, d)
print(my_sentence)
可能的输出#1:
"This is my pig and this is my pig."
可能的输出#2
"This is my dog and this is my pig."
一种可能的解决方法是使用OrderedDict。
from collections import OrderedDict
def replace_all(text, dic):
for i, j in dic.items():
text = text.replace(i, j)
return text
od = OrderedDict([("cat", "dog"), ("dog", "pig")])
my_sentence = "This is my cat and this is my dog."
replace_all(my_sentence, od)
print(my_sentence)
下面是一个简单的例子,它应该可以实现正则表达式的功能:
例如:
为什么没有这样的解决方案?
你可以做一个很好的循环函数。
其中,
text
是完整的字符串,dic
是一个字典-每个定义都是一个字符串,将替换与该术语匹配的字符串。注意:在Python 3中,
iteritems()
已替换为items()
小心:Python字典没有可靠的迭代顺序。此解决方案仅在以下情况下解决您的问题:
例如:
可能的输出#1:
可能的输出#2
一种可能的解决方法是使用OrderedDict。
输出:
小心2:如果
text
字符串太大或字典中有许多对,则效率低下。相关问题 更多 >
编程相关推荐