use*_*113 22 python string replace
我需要帮助我用Python编写的程序.
假设我想每一个字的情况下更换"steak"到"ghost"(只是用它去......),但我也希望每一个字的情况下更换"ghost"到"steak"在同一时间.以下代码不起作用:
s="The scary ghost ordered an expensive steak"
print s
s=s.replace("steak","ghost")
s=s.replace("ghost","steak")
print s
Run Code Online (Sandbox Code Playgroud)
它打印: The scary steak ordered an expensive steak
我想要得到的是 The scary steak ordered an expensive ghost
mgi*_*son 24
我可能在这里使用正则表达式:
>>> import re
>>> s = "The scary ghost ordered an expensive steak"
>>> sub_dict = {'ghost':'steak','steak':'ghost'}
>>> regex = '|'.join(sub_dict)
>>> re.sub(regex, lambda m: sub_dict[m.group()], s)
'The scary steak ordered an expensive ghost'
Run Code Online (Sandbox Code Playgroud)
或者,作为可以复制/粘贴的功能:
import re
def word_replace(replace_dict,s):
regex = '|'.join(replace_dict)
return re.sub(regex, lambda m: replace_dict[m.group()], s)
Run Code Online (Sandbox Code Playgroud)
基本上,我创建了一个我要用其他单词替换的单词映射(sub_dict).我可以从该映射创建一个正则表达式.在这种情况下,正则表达式"steak|ghost"(或"ghost|steak"- 顺序无关紧要),正则表达式引擎完成其余的工作,即查找非重叠序列并相应地替换它们.
一些可能有用的修改
regex = '|'.join(map(re.escape,replace_dict)) - 允许正则表达式在其中具有特殊的正则表达式语法(如括号).这会转义特殊字符以使正则表达式与文字文本匹配.regex = '|'.join(r'\b{0}\b'.format(x) for x in replace_dict) - 如果我们的一个单词是另一个单词中的子字符串,请确保我们不匹配.换句话说,he改为she但不the改为tshe.nne*_*neo 12
用一个目标拆分字符串,进行替换,然后将整个部分放回原处.
pieces = s.split('steak')
s = 'ghost'.join(piece.replace('ghost', 'steak') for piece in pieces)
Run Code Online (Sandbox Code Playgroud)
这完全一样.replace(),包括忽略单词边界.所以它会"steak ghosts"变成"ghost steaks".
将其中一个单词重命名为文本中未出现的临时值。请注意,对于非常大的文本,这不是最有效的方法。为此,are.sub可能更合适。
s="The scary ghost ordered an expensive steak"
print s
s=s.replace("steak","temp")
s=s.replace("ghost","steak")
S=s.replace("temp","steak")
print s
Run Code Online (Sandbox Code Playgroud)