Python-从txt文件获取值

时间:2018-12-14 10:16:40

标签: python-3.x

我正在尝试从txt文件中获取一些值,其中行具有特定的字符串。我的文本文件包含更多数据,如下所示,

2018-11-11 00:00:10 INFO ProtocolProcessor:417 - PUBLISH on server 80 from clientID <ClientId> on topic </data/AClientData> with QoS MOST_ONE
2018-11-11 00:00:10 INFO ProtocolProcessor:530 - Received Msg:{
"id" : "A001",
"val" : 62.0,
"ts" : "2018-11-10 23:41:21"
}
2018-11-11 00:00:10 INFO ProtocolProcessor:587 - send publish message to <tcp://35.166.43.154:80> on topic </data/BClientData>
2018-11-11 00:00:11 INFO Consumer:39 - Received a message of type PUBLISH
2018-11-11 00:00:11 INFO Consumer:58 - String received before queue:{
"id" : "B001",
"val" : 89.0,
"ts" : "2018-11-10 23:42:21"
} 

在上面的文本中,我要按以下格式打印收到的消息:行包含/ data / AClientData

id =A001,
value = 62.0
date = 2018-11-10 23:41:21

尝试过的代码:

searchString = '/data/AClientData'
search = open("C:\\ReadLogUsingPython.txt","r")
for line in search.readlines():
    if searchString in line:
        #here need to take value of next line Received Msg:{ }
        #print each value
        valueDict ={"id" : "A001","val" : 62.0,"ts" : "2018-11-10 23:41:21"}
        print(valueDict['id'])
        print(valueDict['val'])
        print(valueDict['ts']) 

2 个答案:

答案 0 :(得分:1)

这是使用简单迭代的一种方法。

例如:

with open(filename) as infile:
    for line in infile:
        if "/data/AClientData" in line:
            next(infile)
            extractData = [next(infile).strip().replace('"', "") for i in range(3)]
            for i in extractData:
                print("{}={}".format(*i.split(" : ")))

输出:

id=A001,
val=62.0,
ts=2018-11-10 23:41:21

答案 1 :(得分:0)

要做类似的事情,我将逐个字符扫描<>围栏,然后将内容与{和{{ 1}}。例如

}

我在电话上键入了此信息,因此请原谅任何错误。但这是一个粗略的主意。