質問
どのように私はPythonでEOFのためにチェックしますか?私は、セパレータの後のテキストの最後のブロックは、戻りリストに追加されていない私のコードにバグを発見しました。それとも、この機能を表現する良い方法はあります?
ここに私のコードです:
def get_text_blocks(filename):
text_blocks = []
text_block = StringIO.StringIO()
with open(filename, 'r') as f:
for line in f:
text_block.write(line)
print line
if line.startswith('-- -'):
text_blocks.append(text_block.getvalue())
text_block.close()
text_block = StringIO.StringIO()
return text_blocks
解決
あなたはそれが簡単に itertools.groupby 。
def get_text_blocks(filename):
import itertools
with open(filename,'r') as f:
groups = itertools.groupby(f, lambda line:line.startswith('-- -'))
return [''.join(lines) for is_separator, lines in groups if not is_separator]
別の方法としては、セパレータにマッチする正規表現を使用することです。
def get_text_blocks(filename):
import re
seperator = re.compile('^-- -.*', re.M)
with open(filename,'r') as f:
return re.split(seperator, f.read())
他のヒント
ファイル終了条件は、すぐfor
文終了として保持している - minorly修正する最も簡単な方法は、このコードと思われる(あなたはそれを追加する前に空にいない確認したい場合は、最後にtext_block.getvalue()
を抽出することができます)ます。
これはバッファを放出すると、標準的な問題である。
あなたはEOFを検出しません - 無用だという。あなたは最後のバッファを作成します。
def get_text_blocks(filename):
text_blocks = []
text_block = StringIO.StringIO()
with open(filename, 'r') as f:
for line in f:
text_block.write(line)
print line
if line.startswith('-- -'):
text_blocks.append(text_block.getvalue())
text_block.close()
text_block = StringIO.StringIO()
### At this moment, you are at EOF
if len(text_block) > 0:
text_blocks.append( text_block.getvalue() )
### Now your final block (if any) is appended.
return text_blocks
なぜ、あなたはここではStringIOが必要なのでしょうか?
def get_text_blocks(filename):
text_blocks = [""]
with open(filename, 'r') as f:
for line in f:
if line.startswith('-- -'):
text_blocks.append(line)
else: text_blocks[-1] += line
return text_blocks
EDIT:固定機能、他の提案は、より良い、ちょうどオリジナルのものと同様の機能を書きたいと思ったことがあります。
。EDIT:でファイルが始まると仮定「 - - 」、リストに空の文字列を追加することによって、あなたは、「修正」はIndexErrorか、このいずれかを使用できます。
をdef get_text_blocks(filename):
text_blocks = []
with open(filename, 'r') as f:
for line in f:
if line.startswith('-- -'):
text_blocks.append(line)
else:
if len(text_blocks) != 0:
text_blocks[-1] += line
return text_blocks
しかし、両方のバージョンは、REG-EXバージョンがはるかにきれいである私には醜いビットを見ます。
これは、空のファイルを持っているかどうかを確認するために高速な方法であります
if f.read(1) == '':
print "EOF"
f.close()
所属していません StackOverflow