python - 解析传入字节流的最佳方法?

标签 python parsing

我想知道从文件中查找字节流中的开始和结束序列的最佳方法是什么。我这样做的方式是:

begin_msg = [b'B', b'E', b'G', b'I', b'N', b'_', b'M', b'S', b'G', b'#']
end_msg = [b'#', b'E', b'N', b'D', b'_', b'M', b'S', b'G']

with open(file, 'rb') as _file:

begin_id = [b'', b'', b'', b'', b'', b'', b'', b'', b'', b'']
end_id = [b'', b'', b'', b'', b'', b'', b'', b'']

if True:

    byte = _file.read(1)

    capturing = False

    while byte != b'':

        begin_id.append(byte)
        begin_id.pop(0)
        end_id.append(byte)
        end_id.pop(0)

        if begin_id == begin_msg:
            capturing = True

        if end_id == end_msg:
            capturing = False
            break

        byte = _file.read(1)

        if capturing:
            byte_message += byte

我确信有更好的方法来做到这一点。查找这些开始和结束标识符的最简洁方法是什么?

最佳答案

你想做的事情听起来像Python的re正则表达式(aka regex)模块可以处理。如果您向其传递一个要解析的字节字符串并将模式定义为字节字符串,则可以使用它来解析字节字符串(而不是通常的文本字符串)。注意:最简单的方法是在它们前面使用 b 字符串前缀(而不是像您在问题中那样在每个字符前面使用)。

为了测试即将出现的代码,我使用了一个包含此内容的文件(抱歉,不太有想象力):

BEGIN_MSG#
Douglas was here.
#END_MSG
Other stuff
in here.
BEGIN_MSG#
And so
was Roger.
#END_MSG

然后使用正确的正则表达式模式在其上使用模块,如下所示:

import re

pattern = rb'BEGIN_MSG#(.+?)#END_MSG'
filename = 'bytestream.txt'

with open(filename, 'rb') as file:
    matches = re.findall(pattern, file.read(), flags=re.DOTALL)
    if not matches:
        print('No matches found')
    else:
        print('Matches:')
        for i, match in enumerate(matches, 1):
            print('#{}: {}'.format(i, match))

它的输出如下所示,显示从 re.findall() 返回的字符串列表:

Matches:
#1: b'\r\nDouglas was here.\r\n'
#2: b'\r\nAnd so\r\nwas Roger.\r\n'

关于python - 解析传入字节流的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47296595/

相关文章:

python - 如何避免 django "clashes with related m2m field"错误?

python - 禁止 : 403 User not authorized even though the user is logged in

java - 用于解析未知长度消息的分隔符(最佳实践?)java

iphone - 获取URL的动态内容?

c - 读取文件中前面的行(在 C 中)

python - 使用 ftplib 进行多线程上传

python - 使用 for 循环和 if 语句求根迭代

javascript - 使用类似 markdown 的标记语言递归解析字符串

python - 无法为一副牌赋予数值

objective-c - 从 m4a 或 wav 解析标题?