【问题标题】:Getting the line above a search value in python在python中获取搜索值上方的行
【发布时间】:2011-12-28 07:40:22
【问题描述】:

我有一个文本文件要搜索特定的ip地址,文本文件的设置方式是主机名在ip add上面。即

real HOSTNAME

address xx.xx.xx.xx

当我只获得要搜索的 IP 地址时,获取主机名的最佳/最简单方法是什么?常用表达? python中是否有类似sed的实用程序具有保留空间?任何帮助表示感谢谢谢

【问题讨论】:

    标签: python regex sed multiline


    【解决方案1】:

    正则表达式可能是最简单的解决方案。

    >>> textdata = '''
    someline
    another line
    real HOSTNAME
    
    address 127.0.0.1
    post 1
    post 2
    '''
    >>> re.findall('^(.*)$\n^.*$\naddress 127.0.0.1', textdata, re.MULTILINE)
    ['real HOSTNAME']
    

    您也可以使用linecache module 或使用f.readlines() 将所有行读入一个列表。

    【讨论】:

      【解决方案2】:

      如果您知道主机名在 ip 之前有多少行,那么您可以枚举行列表,并从当前索引中减去必要的行数:

      lines = open("someFile", "r").read().splitlines()
      IP = "10.10.1.10"
      hostname = None
      for i, line in enumerate(lines):
          if IP in line:
              hostname = lines[i - 1]
              break
      
      if hostname:
          # Do stuff
      

      【讨论】:

        【解决方案3】:

        这可能不是最好的解决方案,但您可以使用 deque 捕获目标行上方的 n 行:

        from collections import deque
        from itertools import takewhile
        
        test = """
        real others
        
        address xxx.xxx.xxx
        
        real local
        
        address 127.0.0.1
        
        real others
        
        address xxx.xxx.xxx
        """.split("\n")
        
        pattern = "address 127.0.0.1"
        print deque(takewhile(lambda x:x.strip()!=pattern, test), 2)[0]
        

        将测试变量更改为 file("yourfilename") 以从文本文件中读取行。

        【讨论】:

        • 很好地使用了 maxlen 参数 :-)
        猜你喜欢
        • 2011-02-03
        • 2022-06-19
        • 1970-01-01
        • 2021-11-12
        • 1970-01-01
        • 2014-02-14
        • 1970-01-01
        • 1970-01-01
        • 2022-12-13
        相关资源
        最近更新 更多