python - 在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
有什么帮助吗?
解决方案
使问题具有挑战性的是,您需要收集所有信息才能找到一些结果。
代码
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
推荐阅读
- reactjs - 如何在 React+Graphql 中设置 resetToken?
- laravel - 部署者 Laravel 迁移失败
- c++ - 在 C++ 中声明方法时出现测试问题
- android - 在实现地图视图的两个片段之间共享数据的最佳方式?
- ubuntu - Github Action- 如何重启会话?
- python - 为什么打印格式会抛出 NoneType 错误?
- javascript - JavaScript:无法将 for 循环的索引与另一个数字进行比较
- ansible - Ansible - 调用救援后跳过块中的其他任务
- python - 如何解决Kivy中的“.kv多次加载”错误?
- java - 获取算法的运行时间