9

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
4

5 に答える 5

2

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]

もう 1 つの方法は、正規表現を使用してセパレーターを照合することです。

def get_text_blocks(filename):
    import re
    seperator = re.compile('^-- -.*', re.M)
    with open(filename,'r') as f:
        return re.split(seperator, f.read())
于 2010-01-03T03:56:23.787 に答える
1

これは、バッファの放出に関する標準的な問題です。

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
于 2010-01-03T12:44:08.397 に答える
1

ファイルの終わりの条件は、ステートメントが終了するとすぐに保持されforます。これは、このコードを少し修正する最も簡単な方法のようです (text_block.getvalue()追加する前に空でないことを確認したい場合は、最後に抽出できます)。

于 2010-01-03T03:49:34.910 に答える
-1

なぜここで 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

編集:関数を修正しました。他の提案の方が良いかもしれません。元の関数に似た関数を書きたかっただけです。

編集:ファイルが「---」で始まると仮定すると、リストに空の文字列を追加することで、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

しかし、どちらのバージョンも私には少し見苦しく見えます。正規表現バージョンの方がはるかにクリーンです。

于 2010-01-03T03:55:35.740 に答える
-2

これは、空のファイルがあるかどうかを確認する簡単な方法です。

if f.read(1) == '': 
 print "EOF"
 f.close()
于 2012-04-10T17:28:34.690 に答える