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

标签 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()、...吗?

最佳答案

这是一种奇怪的格式。但您可以轻松地将其剪切以获得您想要的部分。

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'

关于python - 将字符串响应中的特定数据分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19754985/

相关文章:

Python - 从长路径获取文件名

python - 为什么通过ip访问可以,但是域访问失败?

python - 如何解决 'module' 对象没有属性 '_base' 问题?

python - if block 中的语句后出现意外标记 '<newline>'

Python 对串行/以太网无动于衷

python - R: system() 不能使用 .bashrc 中定义的 bash 函数

python - Python 中的 replace() 方法有什么特别之处?

Python 循环导入, `from lib import module` 与 `import lib.module`

python - 在函数: Python中使用特殊字符

Python/Pygame 颜色不是元组 : unhashable type error when used as dictionary keys