如果数据是二进制的,请不要将其读取为文本。将其作为二进制数据读取,然后尝试查找嵌入在二进制数据中的字符串。
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']