-
慕雪6442864
下面是一个应该使用正则表达式的简短示例:import re
rep = {"condition1": "", "condition2": "text"} # define desired replacements here# use these three lines to do the replacementrep
= 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 versionspattern = 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--'
-
牛魔王的故事
你可以做一个很好的循环功能。def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text哪里text是完整的字符串和dic是一个字典-每个定义都是一个字符串,将取代一个匹配的术语。注在Python 3中,iteritems()已被替换为items()小心:Python字典没有可靠的迭代顺序。只有在以下情况下,此解决方案才能解决问题:替换顺序无关更换之前的替换结果是可以的例如:d = { "cat": "dog", "dog": "pig"}mySentence = "This is my cat and this is my dog."replace_all(mySentence, d)print(mySentence)可能的产出#1:"This is my pig and this is my pig."可能的输出#2"This is my dog and this is my pig."一个可能的解决方法是使用OrderedDict。from collections import OrderedDictdef replace_all(text, dic):
for i, j in dic.items():
text = text.replace(i, j)
return text
od = OrderedDict([("cat", "dog"), ("dog", "pig")])mySentence = "This is my cat and this is my dog."replace_all(mySentence, od)
print(mySentence)产出:"This is my pig and this is my pig."小心#2:如果你text字符串太大了,或者字典里有很多对。
-
开心每一天1111
下面是第一种解决方案的变体,如果您喜欢功能的话,可以使用Reduce。*)repls = {'hello' : 'goodbye', 'world' : 'earth'}s = 'hello, world'reduce(lambda a, kv: a.replace(*kv), repls.iteritems(), s)马丁诺的更好版本:repls = ('hello', 'goodbye'), ('world', 'earth')s = 'hello, world'reduce(lambda a, kv: a.replace(*kv), repls, s)