python django解码数组html代码到可读文本

时间:2014-02-04 14:36:45

标签: python django html-encode

我收到一堆二进制数据,我希望它再次成为可读字符串。

# Get data length in bits
dataLen = headerLen + (payLoadLen * 8) - bytes.pos
if dataLen > 0:
        eventData = []
    for i in range(dataLen / 8):
        eventData.append(bytes.read(8).int)
    m.setEventData(eventData)
    logging.debug("[D] Event data: %s" % eventData)

会产生如下日志:

[D]事件数据:[87,84,94,87,44,36,  70,77,83,52,44,48,44,48,44,48,44,48,44,48,44,48,44,48,44,48, 44,48,44,48,44,48,44,48,44,48,44,48,13,10,87,84,94,87,44,36,70,77,83,49,44, 48,44,48,44,48,44,48,44,48,44,48,44,48,44,48,44,48,44,48,44,48,44,48,44,48, 44,48,44,48,44,48,44,48,44,48,44,48,44,48,13,10]

如果你看http://www.asciitable.com/,我知道这是正确的。第一个字符确实是WT ^ W,FMS ......

如何更改此代码以使日志记录具有更易读的字符串?

2 个答案:

答案 0 :(得分:1)

您需要将代码转换为字符串字符,然后将字符连接在一起:

myString = ''.join(map(chr, eventData))

如果您很难理解上面的代码看下面的代码 - 它非常相似。两个版本都使用chr()将每个数字ASCI代码转换为单字符字符串,然后将字符串连接在一起。唯一的区别是,在之前的版本中,我用一个简单的for循环替换了map()

characters = []
for code in eventData:
    characters.append(chr(code))
myString = ''.join(characters)

答案 1 :(得分:1)

要解码字符,您需要使用chr内置字符。要将它们连接在一起,您需要使用join function from the string library

# Get data length in bits
dataLen = headerLen + (payLoadLen * 8) - bytes.pos
if dataLen > 0:
        eventData = []
    for i in range(dataLen / 8):
        eventData.append(bytes.read(8).int)
    m.setEventData(eventData)
    c = []
    for p in eventData:
        c.append(chr(p))
    out = "".join(c)
    logging.debug("[D] Event data pre: %s" % eventData)
    logging.debug("[D] Event data post: %s" % out)