【问题标题】:How to look through only the next few lines of a txt file in Python如何在 Python 中仅查看 txt 文件的后几行
【发布时间】:2017-08-04 05:42:27
【问题描述】:

我正在使用 for 循环和 if 语句在 Python 中抓取一个文本文件,以确定一行是否具有某些元素并返回这些元素。如果我的元素与键在同一行,这很简单,但我不确定如何创建 txt 文件的“子块”,然后只遍历这些。

我的意思是,如果我有

    WKU  D02807769
SRC  6
APN  427637&
APT  4
ART  292
APD  19820929
TTL  Athletic shoe with pocket
ISD  19851001
NCL  1
ECL  1
EXP  Holtje; Nelson C.
NDR  2
NFG  4
TRM  14
INVT
NAM  Gamm; Robert J.
CTY  St. Louis
STA  MO
ASSG
NAM  Kangaroos U.S.A., Inc.
CTY  St. Louis
STA  MO
COD  02
RLAP
...
...
UREF
PNO  D110163
ISD  19380600
NAM  Andrews
UREF
PNO  D116598
ISD  19390900
NAM  Pick
UREF
PNO  D130845
ISD  19411200
NAM  Pick
UREF

通过查找 WKU 返回“D02807769”很简单,但是如果我只想查看(例如)ASSG 之后但在下一个标签之前的元素(在这种情况下),我不确定如何继续“RLAP”,但它可能是别的东西,尽管行数相同)。

例如,如果我想返回 ASSG 下的 NAM(“Kangaroos U.S.A., Inc.”)的值,但不返回文件中 NAM 的其他值,我不知道该怎么做。

我尝试了一个 while 语句: 而 line.startswith("ASSG") 或 len(line) > 4:

但这似乎给了我一个无限循环。我也试过了

line.next()

但出现错误 AttributeError: '_io.TextIOWrapper' object has no attribute 'next'

我不确定如何在这些间接块中搜索我正在寻找的东西。我认为这是某种 for 循环,但我不知道如何编写它

【问题讨论】:

  • 你确定它总是 4 行吗?或者你需要搜索下一个标签在哪里
  • @ofer sadan 我不确定它是否总是 4 行。我希望能够根据需要调用它(因此,在我的示例中,ASSG 之后的 4 行,以及 INVT 之后的 3 行
  • @JohnDoe 我想问题是,你如何识别一个块,是'块'两行之间的东西,其中两行只包含一个连续的字符串?

标签: python python-3.x parsing


【解决方案1】:

将值的搜索分为两个步骤:

  1. 查找类别 (ASSG)
  2. 找到钥匙 (NAM)

如果您在第 2 步中找到其他类别,请中止搜索。

def find_value(infile, category, key):
    # first, search for the category header - a line with a single word
    for line in infile:
        line= line.strip()
        if line == category:
            # we found the category header, now search for a line that
            # starts with the key
            key = key + ' '
            for line in infile:
                if line.startswith(key):
                    return line[len(key):].lstrip()

                # if this is another category header, stop searching
                line = line.strip()
                if not ' ' in line:
                    break

试运行:

>>> print(find_value(infile, 'ASSG', 'NAM'))
Kangaroos U.S.A., Inc.

或者,您可以使用正则表达式:

import re

def find_value(infile, category, key):
    text = infile.read()
    template = r'(?sm)^{category}$\s+^(?:\S+ +\S[^\n]*$\s+^)*{key}\s+([^\r\n]+)'
    pattern = template.format(category=re.escape(category),
                              key=re.escape(key))
    match = re.search(pattern, text)
    if match is None:
        return None
    return match.group(1)

这个正则表达式的作用几乎相同 - 它搜索等于“ASSG”的行,然后搜索以“NAM”开头的行,如果找到仅包含单个单词的行,则中止搜索.

【讨论】:

    猜你喜欢
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多