如何从Python的串行端口解析实时csv数据?

时间:2019-04-20 03:51:13

标签: python csv parsing pyserial

我是python的新手,我正在尝试创建一个程序,该程序从COM端口(连接到风探测器)获取实时输入,并将实时数据解析为更人性化的输出。当前从端口接收的数据为csv格式:

Q,060,000.10,M,00,19

“ Q”是当前节点地址

“ 060”是风向,

“ 000.10”是风速,

“ M”是单位(m / s)

状态为“ 00”,最后一个数字为校验和。

我能够通过Pyserial readline()获取python打印出连续数据,但是它是默认格式,这不是我想要的格式。我尝试使用csv.reader解析和读取代码,但是我似乎无法以正确的格式打印它。我尝试在其中实现csv.reader,但结果将每个项目都分隔为新行。

这是我用于读取和解析的代码。

while True:
    data = ser.readline().decode('ascii')
    csvReader = csv.reader(data, delimiter=',')
    for row in csvReader:
        print(row)

我现在得到的结果是:

['\x02']
['Q']
['', '']
['', '']
['0']
['0']
['0']
['.']
['0']
['1']
['', '']
['M']
['', '']
['0']
['0']

我正在尝试获得类似于以下内容的最终输出:

"Wind Direction is 60deg. 
Wind Speed is 0.10 m/s. 
The current status is Ok"

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

class kr1
{
    public static void main(String[] args) {
        int a[]= {5,1,3,9,5};
        a=addr (a,0,a.length);
        for (int i:a)
            System.out.print (i +" ");
    }

    static int[] addr(int a[],int i,int n)
    {
        if (i==0)
            addr(a,i+1,n);
        if (i==n-1)
        {
            a[i] = a[i]+a[i-1];
            return a ; //this return statement is not executing
        }
             //this below part is executing even if i has reached to n-1
        a[i] = a[i] + a[i-1];
        addr(a,i+1,n);
        return a;
    }
   }