linux文件内容打印成二进制,如何在二进制文件中只打印可打印字符(相当于Linux下的字符串)?...
在Python3中,以二進(jìn)制模式打開(kāi)文件會(huì)得到bytes的結(jié)果。迭代一個(gè)bytes對(duì)象可以得到0到255(包括0到255)的整數(shù),而不是字符。從^{} 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轉(zhuǎn)換為一個(gè)集合,并對(duì)其進(jìn)行測(cè)試:printable = {ord(c) for c in string.printable}
以及
^{pr2}$
接下來(lái),您希望附加到bytesarray()對(duì)象以保持合理的性能,并從ASCII解碼以產(chǎn)生str結(jié)果: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
與逐個(gè)迭代字節(jié)不同,您可以對(duì)任何可打印的而不是進(jìn)行拆分: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')
我會(huì)嘗試將文件分塊讀取,而不是一次性讀取;不要試圖一次性將大文件放入內(nèi)存中: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')
緩沖區(qū)將任何不完整的單詞從一個(gè)塊帶到下一個(gè)塊;re.split()如果輸入分別以不可打印字符開(kāi)始或結(jié)束,則在開(kāi)始和結(jié)束處生成空值。在
總結(jié)
以上是生活随笔為你收集整理的linux文件内容打印成二进制,如何在二进制文件中只打印可打印字符(相当于Linux下的字符串)?...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: GB28181协议之录像回放
- 下一篇: linux音频声卡 pulseaudi