2014-02-23 26 views
0

我想根据字典中的值替换我的字符串。我想用正则表达式来试试这个。对字符进行分组并执行替换

d = { 't':'ch' , 'r' : 'gh'} 

s = ' Text to replace ' 
m = re.search('#a pattern to just get each character ',s) 
m.group() # this should get me 'T' 'e' 'x' 't' ..... 

# how can I replace each character in string S with its corresponding key: value in my   dictionary? I looked at re.sub() but could figure out how it can be used here. 

我要生成的输出 - > Texch町gheplace

回答

2

使用re.sub

>>> d = { 't':'ch' , 'r' : 'gh'} 
>>> s = ' Text to replace ' 
>>> import re 
>>> pattern = '|'.join(map(re.escape, d)) 
>>> re.sub(pattern, lambda m: d[m.group()], s) 
' Texch cho gheplace ' 

的第二个参数的re.sub可以是一个函数。函数的返回值用作替换字符串。

+0

该程序的作品! ,我想在这里理解第4行,请问你能告诉我什么 - > pattern ='|'.join(地图(re.escape,d))能帮助你吗? – NBA

+0

@NBA,正则表达式't | r'匹配't'或'r'。 – falsetru

+0

@NBA,这个表达式基本上类似于'''.join(['t','r'])',这产生了't | r'。 – falsetru

2

如果在字典中的值没有字符出现在字典中的关键,那么它相当简单。您可以马上使用str.replace功能,这样

for char in d: 
    s = s.replace(char, d[char]) 
print s # Texch cho gheplace 

就更简单了,你可以用下面这将工作,即使键出现在任何字典中的值。

s, d = ' Text to replace ', { 't':'ch' , 'r' : 'gh'} 
print "".join(d.get(char, char) for char in s) # Texch cho gheplace