-1

我正在编写一个 Python 程序来读取文本文件并提取一些信息。我试图找到三个项目,一个实数和两个列表。该脚本将文本文件的行存储为一个列表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 回答
0
#!/usr/bin/env python3
# encoding: utf-8

import sys

def find(haystack, needle, start_line = 0):
    for i, line in enumerate(haystack[start_line:]):
        if line == needle:
            return i + 1
    raise("%s not found." % needle)

def main(argv = None):
    if argv is None:
        argv = sys.argv

    with open(argv[1], 'r') as f:
        text = f.read().splittext()

    find(text, "c", find(text, "b", find(text, "a")))

if __name__ == "__main__":
    sys.exit(main())

我不确定您的意思是“存储在对象中”,但代码很容易修改以适合您的目的。

于 2013-02-18T21:37:03.093 回答