簡體   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