解析传入字节流的最佳方法是什么?

时间:2017-11-14 22:53:09

标签: 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

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

1 个答案:

答案 0 :(得分:1)

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

为了测试即将发布的代码我在其中使用了一个文件(对不起,不是很富有想象力):

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

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

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'
相关问题