简体   繁体   English

在 python 中的文本文件中搜索

[英]Search in text file in python

Hi A text file which has following entries您好 包含以下条目的文本文件

CHECK>ABC
   Battery:   OK
   RSA:       OK
 Health Check
CHECK>ABC Verbose
   Battery:   OK
     Battery:    voltage 1 2.3v
     Battery:    voltage 2 2.3v
   RSA:       OK       

Health Check健康检查

I would like to get only following from the file我只想从文件中获得关注

   Battery:   OK
   RSA:       OK

I have following code我有以下代码

start=r'^CHECK>ABC$'
end=r'^Health Check'
pattern = r'{p0}(?!.*{p0})(?:.*?{p1}|.*)'.format(p0=start, p1=end)
matches = re.findall(pattern, text, re.DOTALL | re.MULTILINE)
if matches:
    last_match = matches[-1]
    data.append(last_match.split('\n'))
    if not re.search(end, last_match, re.DOTALL | re.MULTILINE):
        print("error_no_end")
else:
    print("error_no_match")

it gives following information in data它在数据中提供以下信息

CHECK>ABC Verbose
   Battery:   OK
     Battery:    voltage 1 2.3v
     Battery:    voltage 2 2.3v
   RSA:       OK       
Health Check

I guess, you are interested in Battery status and RSA status only, if yes, then these lines of code shall help you.我想,您只对电池状态和 RSA 状态感兴趣,如果是,那么这些代码行会对您有所帮助。

data = []
battery_status = re.search(r"\b(Battery)\s*:\s*\b([A-Z]+)\b", text)
data.append(battery_status.group(1) + ": " + battery_status.group(2))
rsa_status = re.search(r"\b(RSA)\s*:\s*\b([A-Z]+)\b", text)
data.append(rsa_status.group(1) + ": " + rsa_status.group(2))

data = "\n".join(data)
print(data)

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

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