简体   繁体   English

在python中解析串行数据

[英]Parsing serial data in python

I'm new to this site and python. 我是这个网站和python的新手。 I've been working on a project that needs to extract variables from incoming serial data and eventually display it. 我一直在从事一个项目,该项目需要从传入的串行数据中提取变量并最终显示它。 I'm currently working on parsing the data and I'm having a bit of trouble. 我目前正在解析数据,但遇到了一些麻烦。 The serial data looks like this for example: 串行数据如下所示:

a3b5f45c9g8a4c10f64;
f4h87d34k9h4j3d3;
h6f54a12a13a14a15b12b13;

There's multiple variables denoted by the letter before the value and they arrive in no particular order. 在值之前,有多个变量由字母表示,并且它们的到达顺序没有特定的顺序。 About once a second the line breaks with a semi-colon. 大约每秒钟用分号中断一行。 The same variable can appear multiple times or not at all per line. 同一变量可能在每行中出现多次或根本不出现。 The closest I've gotten is using regex to find the value between the identifying letter and the next non-number, if that makes sense. 如果可以的话,我得到的最接近的是使用正则表达式在标识字母和下一个非数字之间找到值。 The problem I'm having is that it only returns the first match and then stops. 我遇到的问题是,它仅返回第一个匹配项,然后停止。 I need the variable to be constantly updated. 我需要不断更新变量。 I've been scratching my head for the past few days, any guidance is greatly appreciated. 过去几天我一直在挠头,任何指导都将不胜感激。

import serial
import re

ser = serial.Serial('COM6', 9600, timeout=2)

while True:
  data_raw = ser.readline()
  print(data_raw)

  apples = re.search('a(.+?)\D', data_raw)
  if apples:
    applesvar = apples.group(1)
    print applesvar

  cherries = re.search('c(.+?)\D', data_raw)
  if cherries:
    cherriesvar = cherries.group(1)
    print cherriesvar


ser.close

You are almost there. 你快到了 By using the first line of your example 通过使用示例的第一行

line = 'a3b5f45c9g8a4c10f64'

re.findall('a(.+?)\D', line)
['3', '4']

re.findall('c(.+?)\D', line)
['9', '10']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM