【问题标题】:Optimize byte array escaping performance python优化字节数组转义性能python
【发布时间】: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


【解决方案1】:
import re

ESCAPE_DICT = {
    b'\x00': rb'\z',  # null
    b'"': rb'\q',
    b';': rb'\s',
    b'\\': rb'\\',
    b'\n': rb'\n',  # linefeed
    b'\f': rb'\f',  # formfeed
    b'\r': rb'\c',  # carriage return
}
ESCAPE_CLASS = '[' + ''.join(r'\x' + e.hex() for e in ESCAPE_DICT) + ']'
ESCAPE_REGEX = re.compile(ESCAPE_CLASS.encode())


def escape(string: bytes) -> bytes:
    return re.sub(ESCAPE_REGEX, lambda m: ESCAPE_DICT[m.group(0)], string)


x = b'"abc\ndef\rpqr\x00stu\\xyz"'
y = escape(x)

from pprint import pprint
pprint(ESCAPE_CLASS)
pprint(ESCAPE_REGEX)
pprint(x)
pprint(y)
# =>
# '[\\x00\\x22\\x3b\\x5c\\x0a\\x0c\\x0d]'
# re.compile(b'[\\x00\\x22\\x3b\\x5c\\x0a\\x0c\\x0d]')
# b'"abc\ndef\rpqr\x00stu\\xyz"'
# b'\\qabc\\ndef\\cpqr\\zstu\\\\xyz\\q'

您可以将rb 前缀读取为“原始字节”。

不过,你的逃跑有点奇怪。例如,回车通常是\r,而不是\c\s 通常代表通用空格。

【讨论】:

  • 使用正则表达式将转义延迟缩短了 200us。谢谢沃尔特!
  • 不客气。你介意我添加正则表达式标签以便于查找吗?
  • 已添加,如果您需要编辑其他内容我会批准
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-20
  • 1970-01-01
  • 2019-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多