Python - 解析文件所需的帮助。有没有办法忽略EOF字符?

时间:2016-05-03 18:11:14

标签: python binary ascii non-ascii-characters fileparsing

我有一个二进制文件,我试图从中提取字符串,我很有时间这样做。 :(

我目前的策略是使用Python读取文件(使用以下函数之一:read(),readline()或readlines())。接下来,我通过行解析(char by char)并查找特殊字符'ô',其中大多数情况直接跟随我想要的字符串!最后,我从特殊字符向后解析记录了我认为“有效”的所有字符。

在一天结束时,我想要前行时间戳和行中的下三个字符串。

结果:

在输入示例行#1中,“读取”功能不会读取整行(显示在输出图像中)。我相信这是因为该函数将二进制文件解释为EOF字符,然后它停止读取。

在该示例的第2行中,有时会出现“特殊字符”,但它不是在我想要提取的字符串之后。 :(

有没有更好的方法来解析这些数据?如果没有,有没有办法解决在示例行#1中看到的问题?

当我将行打印为读取时输入数据和结果输出数据的示例。如您所见,使用readlines()时,它不会读取整行 Examples of input data and the resulting output data when I just print the lines as read. As you can see, it does not read through the entire line when using readlines()

我的字符串提取算法,它不是很健壮。 My string extraction algorithm, which is not very robust.

仅供参考,效率不一定是重要的。

2 个答案:

答案 0 :(得分:0)

为什么要使用Python。使用字符串并通过头部管道,例如

    strings /bin/ls | head -3

看看你得到了什么。您也可以为Windows获取字符串。

答案 1 :(得分:0)

如果数据是二进制的,请不要将其作为文本读取。将其作为二进制数据读取,然后尝试查找嵌入在二进制数据中的字符串。

with open("example.tp", "b") as f:
    data = f.read() # produces a bytes object in python 3

现在根据终端字符分割您的数据

parts = data.split(b'\xf4') # f4 is hex code for your o character in latin-1

现在尽可能从每个部分中提取字符串:

from string import ascii_letters, digits

special_chars = '-()&, '
desired_chars = bytes(ascii_letters + digits + special_chars, encoding="ascii")

data = b'0,123\xf4NOPE#Hello world\xf4ignored' # sample data

parts = data.split(b'\xf4')

strings = []
for p in parts[:-1]: # ignore last part as it is never followed by the split char
    reversed_bytes = p[::-1]
    # extract the string
    for i, byte in enumerate(reversed_bytes):
        if byte not in desired_chars:
            chunk = reversed_bytes[:i]
            break
    else:
        chunk = reversed_bytes # all chars were valid
    bytes_ = chunk[::-1]
    bytes_ = bytes_.replace(b',', b'')
    strings.append(bytes_.decode("ascii")) # turn into a str
    # use ascii codec as there should be no non-ascii bytes in your string

print(strings) # prints ['0123', 'Hello world']