【问题标题】:Search for specific line followed by specific line ( TXT file ) in python [closed]在python中搜索特定行,然后是特定行(TXT文件)[关闭]
【发布时间】:2020-05-18 06:09:37
【问题描述】:

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

有什么帮助吗?

【问题讨论】:

  • 欢迎来到 StackOverflow。当您发布问题时,请向我们提供您所做的事情。我们无法为您编写完整的代码。 :)

标签: python file search text line


【解决方案1】:

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

代码

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

【讨论】:

  • 是的,它对我有用,非常感谢,但请原谅我是 python 新手,如何从文件中读取数据并在其上执行相同的代码。
  • 您从问题中编辑的原始代码显示了如何读取文件。
猜你喜欢
  • 2017-03-05
  • 1970-01-01
  • 1970-01-01
  • 2018-07-11
  • 2015-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多