在你的问题和答案中,你必须写尽可能多的说明
outval = re.sub(r'(?i)item3', .......... )
因为有需要更换的物品。
如果要替换 56 个项目怎么办?
.
在我的以下解决方案中,有 5 项要替换,但指令
r.sub(fruiting,text)
只写了一次:
text = '''
OR 125
BA 48
Pr 12
ba 4
Cherry 147
Ba 10
Or 7
OR 6
Orange 2
AP 9
PR 3
Banana 101
or 22
pR 13
'''
. 重新进口
the_items = ('OR','BA','AP','PR','CH')
new_items = ('Orange','Banana','Apple','Pear','Cherry')
corresp = dict(zip(the_items,new_items))
r = re.compile('(%s) *(\d+)' % '|'.join(the_items),
re.IGNORECASE)
def fruiting(ma,longname = corresp):
fresh = '%-12s %s' % (longname[ma.group(1).upper()],
ma.group(2) )
tu = ('OLD: %r\n'
'NEW: %r\n'
%
( ma.group(),fresh) )
print tu
return fresh
print '%s%s' % (text, r.sub(fruiting,text))
结果
OLD: 'OR 125'
NEW: 'Orange 125'
OLD: 'BA 48'
NEW: 'Banana 48'
OLD: 'Pr 12'
NEW: 'Pear 12'
OLD: 'ba 4'
NEW: 'Banana 4'
OLD: 'Ba 10'
NEW: 'Banana 10'
OLD: 'Or 7'
NEW: 'Orange 7'
OLD: 'OR 6'
NEW: 'Orange 6'
OLD: 'AP 9'
NEW: 'Apple 9'
OLD: 'PR 3'
NEW: 'Pear 3'
OLD: 'or 22'
NEW: 'Orange 22'
OLD: 'pR 13'
NEW: 'Pear 13'
.
OR 125
BA 48
Pr 12
ba 4
Cherry 147
Ba 10
Or 7
OR 6
Orange 2
AP 9
PR 3
Banana 101
or 22
pR 13
Orange 125
Banana 48
Pear 12
Banana 4
Cherry 147
Banana 10
Orange 7
Orange 6
Orange 2
Apple 9
Pear 3
Banana 101
Orange 22
Pear 13