下面的代码将逐个字符地遍历数据并在找到映射时替换它。尽管这假设需要替换的每个数据都是绝对唯一的。
def replacer(instring, mapping):
item = ''
for char in instring:
item += char
yield item[:-5]
item = item[-5:]
if item in mapping:
yield mapping[item]
item = ''
yield item
old_values = ('0000}', '0000J', '0000K', '0000L', '0000M', '0000N')
new_values = (' -0', ' -1', ' -2', ' -3', ' -4', ' -5')
value_map = dict(zip(old_values, new_values))
file_snippet = '00000000000000010000}0000000000000000000200002000000000000000000030000J0000100000000000000500000000000000000000000' # each line is >7K chars long and there are over 6 gigs of text data
result = ''.join(replacer(file_snippet, value_map))
print result
在您的示例数据中,这给出了:
0000000000000001 -0000000000000000000020000200000000000000000003 -10000100000000000000500000000000000000000000
如果数据适合这种方式,则更快的方法是将数据拆分为 5 个字符的块:
old_values = ('0000}', '0000J', '0000K', '0000L', '0000M', '0000N')
new_values = (' -0', ' -1', ' -2', ' -3', ' -4', ' -5')
value_map = dict(zip(old_values, new_values))
file_snippet = '00000000000000010000}0000000000000000000200002000000000000000000030000J0000100000000000000500000000000000000000000' # each line is >7K chars long and there are over 6 gigs of text data
result = []
for chunk in [ file_snippet[i:i+5] for i in range(0, len(file_snippet), 5) ]:
if chunk in value_map:
result.append(value_map[chunk])
else:
result.append(chunk)
result = ''.join(result)
print result
这会导致您的示例数据中没有替换,除非您删除前导零,然后您会得到:
000000000000001 -0000000000000000000020000200000000000000000003 -10000100000000000000500000000000000000000000
和上面一样。