先読みする (一度に数文字余分に読む) 必要がある場合は、バッファリングされたファイル オブジェクトが必要です。次のクラスはまさにそれを行います。
import io
class AlphaPeekReader(io.BufferedReader):
def readalpha(self, count):
"Read one character, and peek ahead (count - 1) *extra* characters"
val = [self.read1(1)]
# Find first alpha character
while not val[0].isalpha():
if val == ['']:
return '' # EOF
val = [self.read1(1)]
require = count - len(val)
peek = self.peek(require * 3) # Account for a lot of garbage
if peek == '': # EOF
return val[0]
for c in peek:
if c.isalpha():
require -= 1
val.append(c)
if not require:
break
# There is a chance here that there were not 'require' alpha chars in peek
# Return anyway.
return ''.join(val)
これは、読んでいる 1 文字を超える余分な文字を見つけようとしますが、要件を満たすことができるという保証はありません。ファイルの最後にいる場合、または次のブロックにアルファベット以外のテキストがたくさんある場合は、読み取りが少なくなる可能性があります。
使用法:
with AlphaPeekReader(io.open(filename, 'rb')) as alphafile:
alphafile.readalpha(3)
入力例を含むファイルを使用したデモ:
>>> f = io.open('/tmp/test.txt', 'rb')
>>> alphafile = AlphaPeekReader(f)
>>> alphafile.readalpha(3)
'abc'
>>> alphafile.readalpha(3)
'bcc'
>>> alphafile.readalpha(3)
'ccd'
>>> alphafile.readalpha(10)
'cdfdenhjcd'
>>> alphafile.readalpha(10)
'dfdenhjcde'
readalpha()
各文字と次の 2 バイトを別々に取得するループで呼び出しを使用するにiter()
は、番兵とともに を使用します。
for alpha_with_extra in iter(lambda: alphafile.readalpha(3), ''):
# Do something with alpha_with_extra