将字符串列表转换为浮点列表

问题描述 投票:1回答:1

我试图从微控制器接收串行数据到Python。微控制器使用此C代码通过串行通信输出以下内容。它输出每分钟转数值(浮点)和以返回车架终止的时间值。

 printf("f;%lu\r", appData.rpm, appData.time_elapsed);

在Python中,我有以下代码来获取此串行数据。我想把时间值放在他们自己的数组中,我想将RPM值放在他们自己的数组中。我目前有代码将每行放入一个字符串列表中,rpm和time值作为单独的列。

import serial
import matplotlib.pyplot as plt
import numpy as np
import ast
import io


line = []
ser = serial.Serial(
    port='COM15',\
    baudrate=19200,\
    parity=serial.PARITY_NONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

#Send the start command
print(ser.write('s\r'.encode())) #tell the pic to send data. encode converts to a byte array
ser.close()
ser.open()
#this will store the line
seq = []
count = 1
#variables to store the data numerically
floats = []
time = []
RPM = []
samples = 0
ser.reset_input_buffer()
while True:
    for i in ser.read():
        seq.append(chr(i)) #convert from ASCII and append to array
        joined_seq = ''.join((str)(j) for j in seq) #Make a string from array

        if chr(i) == '\r':
            joined_seq = joined_seq[:-1]
            data = joined_seq.split(',')
            print(data)
            time.append(float(data[0]))
            RPM.append(float(data[0]))
            seq = []
            data = []
            count += 1
            samples +=1
            break

ser.close()

在尝试将字符串转换为浮点数时,我收到如下所示的错误。任何帮助将不胜感激。

['\t\x82\x82\x82bª\x82\x82\x82\x82j0.0000', '100000']
Traceback (most recent call last):
  File "gui.py", line 38, in <module>
    time.append(float(data[0])) ValueError: could not convert string to float: '\t\x82\x82\x82bª\x82\x82\x82\x82j0.0000'
python string-conversion
1个回答
0
投票

试试这个数据部分:

data = '\t\x82\x82\x82bª\x82\x82\x82\x82j0.0000, 100000'
data = joined_seq.decode('ascii', errors='ignore').replace('\t', '').replace('j', '').replace('b', '').split(',')
data
[u'0.0000', u' 100000']

希望这可以帮助

© www.soinside.com 2019 - 2024. All rights reserved.