在 python 中搜索特定行后跟特定行(TXT 文件)
Search for specific line followed by specific line ( TXT file ) in python
我想打印下没有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
有什么帮助吗?
这个问题之所以具有挑战性,是因为您需要收集所有信息才能找到一些结果。
代码
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
我想打印下没有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
有什么帮助吗?
这个问题之所以具有挑战性,是因为您需要收集所有信息才能找到一些结果。
代码
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