![](/img/trans.png)
[英]how to write code to extract a specific text and integer on the same line from a pdf file using python?
[英]How to extract text from a specific line of a text file in Python?
我有一个日志文件,目前存储以下信息:
RTSP0 rtsp://admin:****@192.168.0.104:554/onvif1
RTSP1 rtsp://admin:****@192.168.0.104:554/onvif2
CAMERA_HASH a586c0c691aa7e3fb37d1ff318bf4d6fdb83b24b
RTSP0 rtsp://admin:****@192.168.0.104:554/onvif1
RTSP1 rtsp://admin:****@192.168.0.104:554/onvif2
CAMERA_HASH a586c0c691aa7e3fb37d1ff318bf4d6fdb83b24b
RTSP0 rtsp://admin:****@192.168.0.104:554/onvif1
RTSP1 rtsp://admin:****@192.168.0.104:554/onvif2
CAMERA_HASH a586c0c691aa7e3fb37d1ff318bf4d6fdb83b24b
每次连接相机时,都会将两个新的 RTSP 流(即 RTSP0 和 RTSP1)和一个 HASH 编号添加到日志文件中。 我需要提取最近连接的相机(即最近的 RTSP0 流)的 RTSP stream。 有没有办法通读文件并仅提取这个特定的 stream? 目前,我正在做:
searchfile = open('/Eya/pine_onvif/logs/camera_hash.log', 'r')
search = searchfile.readlines()
stream = []
line_cont = []
streamValue = []
for i,line in enumerate(search):
if 'RTSP0' in line:
line_cont = line
stream = line.split(' ')
streamValue = stream[1]
filename = streamValue
print(streamValue)
searchfile.close()
但是这种方法会产生 output ,如下所示:
rtsp://admin:****@192.168.0.104:554/onvif1
rtsp://admin:****@192.168.0.104:554/onvif1
rtsp://admin:****@192.168.0.104:554/onvif1
我无法仅检索streamValue
数组的最后一行。
对于第二个问题,您应该使用“反向”读取,即从文件末尾循环,然后在找到第一条 rtsp 行后使用简单的break
:
for line in reversed(list(searchfile)):
hash = re.match(r"RTSP[.0-9] (rtsp:\/\/.*)", line.rstrip())
if hash is not None :
print(hash.group(1))
break
模块re
和 regex 是您正在寻找的:
编辑:
import re
searchfile = open('/Eya/pine_onvif/logs/camera_hash.log', 'r')
for line in searchfile:
hash = re.match(r"RTSP[.0-9] (rtsp:\/\/.*)", line)
if hash is not None :
print(hash.group(1))
searchfile.close()
此外,如果你想从文件末尾搜索,你可以改变你的循环:
for line in reversed(list(searchfile)):
hash = re.match(r"RTSP[.0-9] (rtsp:\/\/.*)", line.rstrip())
if hash is not None :
print(hash.group(1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.