在你的问题和答案,你必须写许多指令
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