文字列内の文字列を拡張文字列に置き換える必要があります。
私の質問は、info内の文字列の位置を置き換えるたびに、元の文字列が変更されることです。Pythonの方法で文字列を更新するにはどうすればよいですか?
str = 'If you do not know where you are going, any road will get you there.'
info = {'you': [(3, 3), (25, 3)], 'get you': [(54, 7)], 'know': [(14, 4)]}
# replace 'you' from info with '<b>you</b>' and 'know' with '<i>know</i>'
# results in
str = 'If <b>you</b> do not <i>know</i> where <b>you</b> are going, any road will get you there.'
info = {'<b>you</b>': [(3, 10), (25, 10)], 'get you': [(54, 7)], '<i>know</i>': [(21, 11)]}
これまでの私の解決策:
str = 'If you do not know where you are going, any road will get you there.'
info = {'you': [(3, 3), (25, 3)], 'get you': [(54, 7)], 'know': [(14, 4)]}
replacer = [('you', '<b>you</b>'), ('know', '<i>know</i>')]
for s, s2 in replacer:
print "replacing %s to %s and update position info dict" % (s, s2)
old_s_pos = info[s]
diff = len(s2) - len(s)
new_key_pos = [(old_s_pos[0][0], old_s_pos[0][1] + diff)]
old_s_pos = old_s_pos[1:]
if old_s_pos:
next_old_s_pos_start = old_s_pos[0][0]
else:
next_old_s_pos_start = None
del info[s]
for key, positions in info.iteritems():
new_positions = []
for i, (x,y) in enumerate(positions):
if x < next_old_key_pos_start:
new_positions.append((x + diff, y))
else:
new_positions.append((x, y))
if next_old_s_pos_start is not None:
# update old_s_pos at first pair
new_key_pos.append((old_key_pos[0][0], old_s_pos[0][1] + diff))
old_s_pos = old_s_pos[1:]
if old_s_pos:
next_old_s_pos_start = old_s_pos[0][0]
info[key] = new_positions
info[s2] = new_key_pos
print info
よろしく、マティアス