使用 Python 从文本文件中提取 StatusDescription

Extracting the StatusDescription from a text file using Python

我有一个示例文本文件。我想为每一行提取 StatusDescription,以防它不可用,我希望它 return 为空,即

Line1 StatusDescription=空

第 2 行 StatusDescription=成功

示例文本文件:

[2019 年 10 月 23 日][12:14:49:150][[ACTIVE]ExecuteThread:'7'队列:'weblogic.kernel.Default (self-tuning)'][22368936][172.30.26.90][c84283f4- 5a3d-4559-b8d1-6ae2bdfc6075][com.intellectdesign.iportal.as.integrator.host.GenericCommunicator][退出] {离开 sendToHostEx 方法...}

[2019 年 10 月 23 日][12:14:49:150][[ACTIVE]ExecuteThread:'7'队列:'weblogic.kernel.Default (self-tuning)'][22368936][172.30.26.90][c84283f4- 5a3d-4559-b8d1-6ae2bdfc6075][com.intellectdesign.digitalface.formatter.CoopCardSummmaryFormatter][错误] {hdr_Tran_Id=COOP_CARD_DETAILS~*hdr_Ref_No=1~*res_Status=00000~* CorrelationID=AAAAAD7B5619~*MessageID=AAAAAD7B5619~*StatusCode=S_001~*StatusDescription=成功~*StatusDescriptionKey=en-US}

这应该适用于您的情况:

import re

def find_substring(line):
    try:
        result = re.search('StatusDescription=(.*)~', line)
        return result.group(1)
    except:
        return "Null"

with open('text.txt') as f:
    lines = f.readlines()
    for line in lines:
        status_description = find_substring(line)
        print(status_description)