在python中搜索特定行,然后搜索特定行(TXT文件)

问题描述 投票:0回答:1

我想打印没有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

任何帮助吗?

python file search text line
1个回答
0
投票
使问题具有挑战性的是,您需要先收集所有信息,然后才能找到一些结果。

代码

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

© www.soinside.com 2019 - 2024. All rights reserved.