将字符串响应中的特定数据分配给变量

时间:2013-11-03 16:10:48

标签: python

我的代码:

#Importing the urllib tool to my program
import urllib.request

#Fetch data from URL
response = urllib.request.urlopen('<URL>')

#Store that response into the variable below
taginfo = response.read()

#Tag info result of search for SSI values
taginforesult = taginfo

#print taginfo
print(taginfo)

以上Python Shell中的结果如下:

b'LOCATE00016331: tagid="00016331", taggroupid=LOCATE, tagtype=mantis04A, irlocator=null, motion=false, tamper=false, panic=false, lowbattery=false, locationzone="", gpsid="", lastgpsid="", lastgpsts=null, confidencebyrule={}\r\n(CarrierHQ_channel_A: reader=CarrierHQ, channel="A", ssi=-95)\r\n(CarrierHQ_channel_B: reader=CarrierHQ, channel="B", ssi=-99)\r\n\r\n\r\n'

我想知道的是:如何从上面的响应中仅选择SSI=-95SSI-99值,然后将其插入SSI-ASSI-B变量?

strip()findall()search(),......?

1 个答案:

答案 0 :(得分:1)

这是一种奇怪的格式。但是你可以轻松切割它以获得你想要的部件。

ssia = str(taginfo).split("\\r\\n")[1]
                   .strip("()")
                   .split(",")[-1]
                   .strip()
                   .split("=")[1]
assert ssia == '-95'

ssib = str(taginfo).split("\\r\\n")[2]
                   .strip("()")
                   .split(",")[-1]
                   .strip()
                   .split("=")[1]    
assert ssib == '-99'