首页 > 解决方案 > 在python中搜索特定行,然后是特定行(TXT文件)

问题描述

我想打印下面没有 qos 的接口,我有如下 txt 文件

interface 1
 qos
 trust
interface 2
 trust
interface 3
 trust
 qos
interface 4
 trust 
 trust
 qos
interface 5
 trust
interface 6

我希望输出如下(需要输出):

interface 2
interface 5
interface 6

有什么帮助吗?

标签: pythonfilesearchtextline

解决方案


使问题具有挑战性的是,您需要收集所有信息才能找到一些结果。

代码

def no_qos(lines):
    # keep track of interfaces seen and which has qos
    interfaces = []
    has_qos = set()

    # scan the file and gather interfaces and which have qos
    for line in lines:
        if not line.startswith(' '):
            interface = line.strip()
            interfaces.append(interface)
        elif line.startswith(" qos"):
            has_qos.add(interface)

    # report which interfaces do not have qos
    return [i for i in interfaces if i not in has_qos]

测试代码:

data = '''
interface 1
 qos
 trust
interface 2
 trust
interface 3
 trust
 qos
interface 4
 trust
 trust
 qos
interface 5
 trust
interface 6
'''

for interface in no_qos(data.split('\n')):
    print(interface)

结果:

interface 2
interface 5
interface 6

推荐阅读