我有一些文件,其中包含一堆不同类型的二进制数据,我正在编写一个模块来处理这些文件。
其中,它包含以下格式的 UTF-8 编码字符串:2 字节大端 stringLength(我使用 struct.unpack() 解析),然后是字符串。由于它是 UTF-8,字符串的字节长度可能大于 stringLength 并且如果字符串包含多字节字符,则执行 read(stringLength) 将变得很短(更不用说搞乱所有文件中的其他数据)。
如何在了解 UTF-8 的多字节属性的情况下从文件中读取 n 个 UTF-8 字符(不同于 n 字节)?我已经用谷歌搜索了半个小时,但我发现的所有结果要么不相关,要么做出了我无法做出的假设。
最佳答案
给定一个文件对象和一些字符,您可以使用:
# build a table mapping lead byte to expected follow-byte count
# bytes 00-BF have 0 follow bytes, F5-FF is not legal UTF8
# C0-DF: 1, E0-EF: 2 and F0-F4: 3 follow bytes.
# leave F5-FF set to 0 to minimize reading broken data.
_lead_byte_to_count = []
for i in range(256):
_lead_byte_to_count.append(
1 + (i >= 0xe0) + (i >= 0xf0) if 0xbf < i < 0xf5 else 0)
def readUTF8(f, count):
"""Read `count` UTF-8 bytes from file `f`, return as unicode"""
# Assumes UTF-8 data is valid; leaves it up to the `.decode()` call to validate
res = []
while count:
count -= 1
lead = f.read(1)
res.append(lead)
readcount = _lead_byte_to_count[ord(lead)]
if readcount:
res.append(f.read(readcount))
return (''.join(res)).decode('utf8')
测试结果:
>>> test = StringIO(u'This is a test containing Unicode data: \ua000'.encode('utf8'))
>>> readUTF8(test, 41)
u'This is a test containing Unicode data: \ua000'
在 Python 3 中,将文件对象包装在 io.TextIOWrapper()
object 中当然容易得多并将解码留给 native 和高效的 Python UTF-8 实现。
关于python - 从二进制文件中读取 UTF-8 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15199675/