【问题标题】:Extract Bytes From String That Contains Bytes Data从包含字节数据的字符串中提取字节
【发布时间】:2020-01-11 18:23:03
【问题描述】:

我是 python 3 的新手,并试图从包含消息中字符串和字节的字节数组中提取消息。

我无法从解码字节数组中提取字节消息。

  1. 首先,我对字节数组进行解码。
  2. 然后我对解码后的数组进行拆分。
  3. 拆分数组时得到字符串值。

我尝试使用bytes(v) for v in rest.split() 函数尝试获取字节数组,然后对其进行解码,但未能成功。

# The message chunk:
chunk = b"1568077849\n522\nb'l5:d4:auth53:\xc3\x99\xc3\xac\x1fH\xc2\xa3ei6eli1eee'\n"

# I split the chunk into sub categories for further processing:
_, size, rest = (chunk.decode("utf-8")).split('\n', 2)

# _ contains "1568077849"
# size contains "522" 
# rest contains "b'l5:d4:auth53:\xc3\x99\xc3\xac\x1fH\xc2\xa3ei6eli1eee'"

我应该能够解码其余变量 (rest.decode("utf-8")),但由于它被存储为字符串,我很难弄清楚如何转换它到字节,然后解码值。

预期结果:l5:d4:auth53:ÙìH£ei6eli1eee

【问题讨论】:

  • 你是怎么得到这个字符串的?似乎有人以错误的方式创建了这个字符串。
  • 你可以使用切片rest = rest[2:-2]
  • 它来自服务器request = reader._build_request(chunk_meta) chunk = urllib.request.urlopen(request).read()
  • 正如@nathancy 提到的,你必须对其进行切片,然后你应该有正确的字符串l5:d4:auth53:ÙìH£ei6eli1eee
  • @nathancy 我需要能够以字节为单位获取值才能正确解码。目前,您的解决方案仍将 rest 作为字符串 ``` print(isinstance(rest, bytes)) -> False ``

标签: python python-3.x


【解决方案1】:

这将打印您的最终结果:

chunk = b"1568077849\n522\nb'l5:d4:auth53:\xc3\x99\xc3\xac\x1fH\xc2\xa3ei6eli1eee'\n"

l1 = chunk.decode('utf-8').split()[2:]  # Initial decode
#  slice out the embedded byte string "b'  '" characters
l1_string = ''.join([x[:-2] if x[0] != 'b' else x[2:] for x in l1])
l1_bytes = l1_string.encode('utf-8')
l1_final = l1_bytes.decode('utf-8')

print('Results')
print(f'l1_string is {l1_string}')
print(f'l1_bytes is {l1_bytes}')
print(f'l1_final is {l1_final}')
Results
l1_string is l5:d4:auth53:ÙìH£ei6eli1ee
l1_bytes is b'l5:d4:auth53:\xc3\x99\xc3\xacH\xc2\xa3ei6eli1ee'
l1_final is l5:d4:auth53:ÙìH£ei6eli1ee

【讨论】:

  • 谢谢戴夫!!花了一些时间来解码答案:)
  • 戴夫,我刚刚发现了数据,它的输入为:chunk = b"1568077849\n522\nb'l5:d4:auth53:\\xc3\\x99\\xc3\\xac\\x1fH\\xc2\\xa3ei6eli1eee'\n"。输入中有两个双斜杠。所以上述解决方案没有按预期工作。
【解决方案2】:

我能够通过这种方式获得预期的输出:

 _, size, rest = (chunk.decode("utf-8")).split('\n', 2)
 rest = bytes(rest.replace("b'", "").replace("'", ""), "utf-8").decode("unicode_escape")

从这篇文章中得到了线索: Process escape sequences in a string in Python

【讨论】:

    猜你喜欢
    • 2011-06-15
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    相关资源
    最近更新 更多