[英]Convert string list to float list
我正在嘗試從微控制器接收串行數據到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'
嘗試使用此數據部分:
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']
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.