繁体   English   中英

如何使用python跨多行读取和匹配

[英]How to read and match across multiple lines with python

我正在尝试从大型文本文件(1000 多行)中提取相关信息,其中大部分并不重要:

 ID: 67108866 Virtual-system: root, VPN Name: VPN-NAME-XYZ
  Local Gateway: 1.1.1.1, Remote Gateway: 2.2.2.2
  Traffic Selector Name: TS-1
  Local Identity: ipv4(10.10.10.0-10.10.10.255)
  Remote Identity: ipv4(10.20.10.0-10.20.10.255)
  Version: IKEv2
  DF-bit: clear, Copy-Outer-DSCP Disabled, Bind-interface: st0.287
  Port: 500, Nego#: 0, Fail#: 0, Def-Del#: 0 Flag: 0x2c608b29 
  Multi-sa, Configured SAs# 1, Negotiated SAs#: 1 
  Tunnel events: 

从中我只需要提取某些位,示例输出将类似于:

VPN Name: VPN-NAME-XYZ, Local Gateway: 1.1.1.1, Remote Gateway: 2.2.2.2

我尝试了几种不同的方法来得到这个,但是我的代码在第一次匹配时一直停止,我需要代码匹配 1 行,然后移动到下一行并匹配:

with open('/path/to/vpn.txt', 'r') as file:
    for vpn in file:
        vpn = vpn.strip().lower()
        name = "xyz"
        if name in vpn:
            print(vpn)
            if "1.1.1.1" in vpn:
                print(vpn)

如果我在行中移动第二个,我可以打印两者:

with open('/path/to/vpn.txt', 'r') as file:
    for vpn in file:
        vpn = vpn.strip().lower()
        name = "xyz"
        if name in vpn:
            print(vpn)
        if "1.1.1.1" in vpn:
            print(vpn)

是否可以在两行上匹配子句? 我尝试了几种不同的方法,我的缩进和匹配但无法得到它, print(vpn)的问题是它正在打印整行

使用正则表达式匹配您需要的区域,然后从整个文本中获取所有匹配。 您也不需要逐行执行此操作。 下面是一个例子。

import re
found_text = []
with open('/path/to/vpn.txt', 'r') as file:
    file_text = file.read()
    [found_text.extend(found.split(",")) for found in [finds.group(0) for finds in
                                                       re.finditer(
                                                           r"((VPN Name|Local Gateway|Remote Gateway):.*)",
                                                           file_text)]]
    # split by comma, if you want it to be splitted further

print(found_text)

这将产生类似的输出

['VPN Name: VPN-NAME-XYZ', 'Local Gateway: 1.1.1.1', ' Remote Gateway: 2.2.2.2']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM