在 Python 中,有时需要对字符串中的多个值进行替换。例如,您可能有一个包含大量数据的固定宽度文件,其中包含一些需要替换的字符串。如果手动进行替换,速度可能会很慢,因此需要一种快速有效的方法来完成此任务。
2. 解决方案
使用 replacer
函数进行逐个字符替换
一种快速替换字符串的方法是使用 replacer
函数。此函数可以对字符串进行字符级别的替换,速度很快。以下是 replacer
函数的示例:
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
此函数需要两个参数:instring
和 mapping
。instring
是要被替换的字符串,mapping
是一个字典,其中包含需要替换的字符串及其替换值。
例如,以下代码将使用 replacer
函数来替换字符串中的某些值:
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
使用 mapping
字典进行替换
另一种快速替换字符串的方法是使用 mapping
字典。mapping
字典是一个键值对的集合,其中键是需要替换的字符串,值是替换值。
例如,以下代码将使用 mapping
字典来替换字符串中的某些值:
old_values = ('0000}', '0000J', '0000K', '0000L', '0000M', '0000N')
new_values = (' -0', ' -1', ' -2', ' -3', ' -4', ' -5')
mapping = 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 mapping:
result.append(mapping[chunk])
else:
result.append(chunk)
result = ''.join(result)
print result
输出结果为:
000000000000001 -0000000000000000000020000200000000000000000003 -10000100000000000000500000000000000000000000
使用 zip
函数和 replace
方法进行替换
最后,还可以使用 zip
函数和 replace
方法来替换字符串中的多个值。zip
函数用于将两个或多个列表中的元素一一对应起来,形成一个元组列表。replace
方法用于将字符串中的某个值替换为另一个值。
例如,以下代码将使用 zip
函数和 replace
方法来替换字符串中的某些值:
old_values = ('0000}', '0000J', '0000K', '0000L', '0000M', '0000N')
new_values = (' -0', ' -1', ' -2', ' -3', ' -4', ' -5')
file_snippet = '00000000000000010000}0000000000000000000200002000000000000000000030000J0000100000000000000500000000000000000000000' # each line is >7K chars long and there are over 6 gigs of text data
for old_value, new_value in zip(old_values, new_values):
file_snippet = file_snippet.replace(old_value, new_value)
print(file_snippet)
输出结果为:
000000000000001 -0000000000000000000020000200000000000000000003 -10000100000000000000500000000000000000000000
这三种替换字符串的方法都非常快速,您可以根据自己的需要选择最合适的方法。