【问题标题】:Print string "Image" along with matching pattern in the text file in Python在 Python 的文本文件中打印字符串“Image”以及匹配的模式
【发布时间】:2017-05-05 04:13:07
【问题描述】:

我是 python 新手。我的文本文件包含以下信息

15:50:12 RECID: C642 SORD=000000000 Image=000000001
15:50:12 STEP 2: BUILD ICC KEY MAINTENANCE
15:50:12 RECID: C642 Image=000000000 EORD=000000007
15:50:12 STEP 3: COUNT OF RECORDS UDPATED
02:26:12 CPSE0152E 02.26.13 IS-0001 SS-BSS  SSU-BSS  SE-008965 Image -UE027A0
02:26:12 010000A ABC-HS52                                                 
02:26:12 HS52    DEF-hs52            

第 5 行 (02:26:12) 将包含“SE-”和“Image”-XXXXXXX”,其中 XXXXXXX=Image 的类型strong> 按编码转储。 下一行将有“ABC-XXXX”,其中 XXXX = 段名称 第 3 行应该有“DEF-XXXX”。我们只需要这 3 行。

Image”关键字可以出现在很多地方,但我想搜索“Image”名称以及下一行信息“ABC-XXXX”和“ DEF-XXXX” 并打印接下来的 2 行文本

我的输出应该是

02:26:12 CPSE0152E 02.26.13 IS-0001 SS-BSS  SSU-BSS  SE-008965 Image-UE027A0
02:26:12 010000A ABC-HS52                                                 
02:26:12 HS52    DEF-hs52  

【问题讨论】:

  • 尽可能避免使用正则表达式。

标签: python regex if-statement text


【解决方案1】:

这是一个可以为您提供所需内容的工作示例。假设您的输入文件称为“输入”。

with open("input", "r") as file:
    output = ""

    for line in file.readlines():
        if "Image" in line:
            output += line
        elif "ABC" in line and "Image" in output:
            output += line
        elif "DEF" in line and "ABC" in output:
            output += line
        else:
            output = ""

    print(output)

【讨论】: