【发布时间】:2021-12-02 05:38:44
【问题描述】:
我需要在 python 中对字节数组执行自定义转义。但是,python 在转义过程中会将字节转换为整数,使得性能优化变得非常困难。如何加快转义功能?
ESCAPE_DICT={
0x00: [0x5C,0x7A], # null -> \z 0x5c 0x7a
0x22: [0x5C,0x71], # " -> \q 0x5c 0x71
0x3B: [0x5C,0x73], # ; -> \s 0x5c 0x73
0x5C: [0x5C,0x5C], # \ -> \\ 0x5c 0x5c
0x0A: [0x5C,0x6E], # line-feed -> \n 0x5c 0x6e
0x0C: [0x5C,0x66], # form-feed -> \f 0x5c 0x66
0x0D: [0x5C,0x63], # carr-return -> \c 0x5c 0x63
}
def escape(string: bytes):
str_len=string.__len__()
escaped_list=[]
for i in range(0,str_len):
curr_byte=string[i]
escape = ESCAPE_DICT.get(curr_byte)
if escape is None:
# Don't escape current byte
escaped_list.append(curr_byte)
else:
# Escape current byte
escaped_list.extend(escape)
return bytes(escaped_array)
【问题讨论】:
-
问题是我必须对字符串执行 N 次循环,其中 N 是可能的转义模式的数量
-
我有一个不同的实现,但这看起来也不错。你能提供一个不起作用的测试用例吗?为什么需要循环转义模式?
-
@KennyOstrom 问题不在于它不起作用。但在这里,我希望提高算法的性能。
标签: python python-3.x regex re