将c++文本编码器重写为python

2024-04-25 06:03:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我用c++编写了以下代码:

for(const char *x = r.ptr, *end = r.ptr + r.len; x != end; ++x) { 
    switch(*x) {
        case 0x5c:
        case 0x22:
            pc->output[0] = '\\'; pc->output[1] = *x; pc->output += 2;
            break;
        case 0xa:
            pc->output[0] = '\\'; pc->output[1] = 'n'; pc->output += 2;
            break;
        case 0xd:
            pc->output[0] = '\\'; pc->output[1] = 'r'; pc->output += 2;
            break;
        default:
            if(str_escape_2_hex(*x)) {
                impl::escape_char_hex(pc->output, *x);
            } else {
                *pc->output = *x; pc->output++;
            }
    }
}

我想把它重写成python2,因为我需要相同的编码器。我试过这个:

def encode_akv_fields(data):
    hexlify = codecs.getencoder('hex')
    for i, el in enumerate(str(data)):
        if hexlify(el)[0] in ('5c', '22'):  # \\ or "
            data[i].encode('hex') = '\\' + hexlify(el)[0]
        elif hexlify(el)[0] == '0a':  # \n
            data[i].encode('hex') = '\\n'
        elif hexlify(el)[0] == '0d':  # \r
            data[i].encode('hex') = '\\r'
        elif '1f' >= hexlify(el)[0] >= '7f':
            tmp3 = (hexlify(el)[0] >> 4) & '0f'.decode('hex')
            data[i].encode('hex') = '\\x'
    return data

但没用-我有

SyntaxError: can't assign to function call

数据是一个字符串或dict,其中包含我要记录的值。这些日志需要采用AKV格式(Apache键值)。为了让它工作,我需要一些十六进制值被编码,就像在c++中一样(c++中的代码可以工作)。你知道吗

如何在python中创建与在c++中相同的编码器?你知道吗


Tags: 代码foroutputdataelencodeendcase