-1

テキストファイルを読み込んで情報を引き出すPythonプログラムを書いています。私が見つけようとしている項目は 3 つあり、実数が 1 つ、リストが 2 つです。このスクリプトは、テキスト ファイルの行をリストとして保存しますinLines。スクリプトが使用する行を読み進めるfor curLine in inLines:と、すべての行で特定のキーが検索されます。残りの部分を関数に渡したい検索キーを見つけたら、inLinesさらに数行読んでから、関数が中断した行のメイン スクリプトに戻ります。

これが私がやりたいことの小さな図です(コメントとして与えられたコードの指示)

line of text that doesn't matter    #Read by main, nothing interesting happens
line of text that doesn't matter    #Read by main, nothing interesting happens
search key A                        #Read by main, all following lines passed to function A
line that matters                   #Read by function A, stores in object
line that matters                   #Read by function A, stores in object

line that matters                   #Read by function A, stores in object


search key B                        #Read by function A, return to main, all following lines passed to function B


line that matters                   #Read by function B, stores in object

search key C                        #Read by function B, return to main, all following lines passed to function C
line that matters                   #Red by function C, stores in object

したがって、各検索キーはプログラムにどの機能を使用するかを指示します (また、異なるキーの順序は任意です)。スクリプトがキーを見つけると、それ以降のすべての行を正しい関数に渡します。関数が検索キーを見つけるたびに、それを中断し、それ以降のすべての行を main に戻します (その後、同じ行を適切な関数に渡します)。

質問の本で申し訳ありません。私は何年ものFORTRANの後にPythonを学んでいるので、誰かがこれについてもっと良い方法を考えることができれば、私は提案を受け入れます. 前もって感謝します

4

3 に答える 3

1

この小さなスクリプトは、あなたが望むものに近いものです。検索機能が指定される前に発生した行を破棄します。あなたはそれをあなたのニーズに適応させることができるはずです。

import sys


def search_func_a(l):
    """
    Called for things that follow `search key A`
    """
    print 'A: %s' % l


def search_func_b(l):
    """
    Called for things that follow `search key B`
    """
    print 'B: %s' % l


def search_key_func(l):
    """
    Returns the associated "search function" for each search string.
    """
    if 'search key A' in l:
        return search_func_a
    if 'search key B' in l:
        return search_func_b
    return None


def main():
    # Start with a default handler.  This changes as `search key` lines are
    # found.
    handler = lambda _: 0 

    for line in open('test.txt'):
        # search_key_func returns None for non `search key` lines.  In that
        # case, continue to use the last `search function` found.
        search_func = search_key_func(line) 
        if search_func:
            # If a search line is found, don't pass it into the search func.
            handler = search_func
            continue
        handler(line)


if __name__ == '__main__':
    sys.exit(main())
于 2013-02-18T20:55:12.493 に答える
0

このようなことをしても問題はありますか?

inA = inB = inC = False
for line in file:
  if keyA(line):
    inA = True
    inB = inC = False
  elif keyB(line):
    inB = True
    inA = inC = False
  elif keyC(line):
    inC = True
    inA = inB = False
  if inA:
    processA(line)
  if inB:
    processB(line)
  if inC:
    processC(line)

より速い方法があるかどうか尋ねていますか?

于 2013-02-18T20:30:10.037 に答える