我使用的是我通过Python3 socket
图书馆连接的LabVIEW模拟器
import socket
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ip=socket.gethostbyname("127.0.0.1")
port=1234
address=(ip,port)
client.connect(address)
while True:
data = client.recv(1024)
print(data)
client.close()
数据输出为:
B'&安培;&安培; \ r \ n0108500.00 \ r \ n01410.000000 \ r \ n01420.000000 \ r \ n01430.000000 \ r \ n01440.000000 \ r \ n01450.000000 \ r \ n0146200.000000 \ r \ n0147100.000000 \ r \ n !! \ r \ n&安培;&安培; \ r \ n0108500.00 \ r \ n01410.000000 \ r \ n01420.000000 \ r \ n01430.000000 \ r \ n01440 0.000000 \ r \ n01450.000000 \ r \ n0146200.000000 \ r \ n0147100.000000 \ r \ n !! \ r \ n'
模拟器输出两个200
和100
的常量值,我对应\r\n0146200.000000\r\n0147100.000000\
0146 and 0147
是来自模拟器的标签ID。什么是解析这些数据的最佳方法(让我们假设这个问题我只想要tagID和最后两个的值)?我试图输出它:
print(data.decode("utf-8", "strict"))
输出:
&安培;&安培; 0108500.00 01410.000000 01420.000000 01430.000000 01440.000000 01450.000000 0146200.000000 0147100.000000 !! &安培;&安培; 0108500.00 01410.000000 01420.000000 01430.000000 01440.000000 01450.000000 0146200.000000 0147100.000000 !!
答案 0 :(得分:1)
使用正则表达式提取键和值:
import re
results = [
dict(re.findall(r"(\d{4})([\d.]+)", string))
for string in filter(
bool, # non-empty
data.decode("utf8", "replace").split("&&"),
)
]
您的数据结果:
[{'0108': '500.00',
'0141': '0.000000',
'0142': '0.000000',
'0143': '0.000000',
'0144': '0.000000',
'0145': '0.000000',
'0146': '200.000000',
'0147': '100.000000'},
{'0108': '500.00',
'0141': '0.000000',
'0142': '0.000000',
'0143': '0.000000',
'0144': '0.000000',
'0145': '0.000000',
'0146': '200.000000',
'0147': '100.000000'}]