linux文件内容打印成二进制,如何在二进制文件中只打印可打印字符(相当于Linux下的字符串)?...
在Python3中,以二進制模式打開文件會得到bytes的結果。迭代一個bytes對象可以得到0到255(包括0到255)的整數,而不是字符。從^{} documentation:While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that 0 <= x < 256
將string.printable轉換為一個集合,并對其進行測試:printable = {ord(c) for c in string.printable}
以及
^{pr2}$
接下來,您希望附加到bytesarray()對象以保持合理的性能,并從ASCII解碼以產生str結果:printable = {ord(c) for c in string.printable}
with open(filename, "rb") as f:
result = bytearray()
for c in f.read():
if c in printable:
result.append(c)
continue
if len(result) >= min:
yield result.decode('ASCII')
result.clear()
if len(result) >= min: # catch result at EOF
yield result
與逐個迭代字節不同,您可以對任何可打印的而不是進行拆分:import re
nonprintable = re.compile(b'[^%s]+' % re.escape(string.printable.encode('ascii')))
with open(filename, "rb") as f:
for result in nonprintable.split(f.read()):
if result:
yield result.decode('ASCII')
我會嘗試將文件分塊讀取,而不是一次性讀取;不要試圖一次性將大文件放入內存中:with open(filename, "rb") as f:
buffer = b''
for chunk in iter(lambda: f.read(2048), b''):
splitresult = nonprintable.split(buffer + chunk)
buffer = splitresult.pop()
for string in splitresult:
if string:
yield string.decode('ascii')
if buffer:
yield buffer.decode('ascii')
緩沖區將任何不完整的單詞從一個塊帶到下一個塊;re.split()如果輸入分別以不可打印字符開始或結束,則在開始和結束處生成空值。在
總結
以上是生活随笔為你收集整理的linux文件内容打印成二进制,如何在二进制文件中只打印可打印字符(相当于Linux下的字符串)?...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: GB28181协议之录像回放
- 下一篇: 纯CSS制作各种各样的网页图标(三角形、