无法将字符串转换为 float-pH 计的 Python 代码

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

我是编码新手,正在尝试使用预先编写的 GUI 代码构建 pH 计。我已经仔细检查了仪器中的所有连接,但 python 代码是最后崩溃的。当我尝试运行仪器时,出现此错误:

    Traceback (most recent call last):
    File "C:\Users\livst\sensors.py", line 353, in updateFigs
    self.data = [float(val) for val in line.split()] # split data to 
    float numbers
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\livst\sensors.py", line 353, in <listcomp>
    self.data = [float(val) for val in line.split()] # split data to 
   float numbers
             ^^^^^^^^^^
    ValueError: could not convert string to float: b'Read'

经过一番阅读后,我尝试使用 文本.解码(“utf-8”) 并通过使用 text.encode("windows-1252").decode("utf-8")

当我使用这些命令时,我在 ValueError 中收到不同文本的相同错误:

Traceback (most recent call last):
  File "C:\Users\livst\sensors.py", line 353, in updateFigs
    self.data = [float(val) for val in line.split()] # split data to float numbers
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\livst\sensors.py", line 353, in <listcomp>
    self.data = [float(val) for val in line.split()] # split data to float numbers
                 ^^^^^^^^^^
ValueError: could not convert string to float: b'H\xf4Read'

这是错误中引用的代码部分:

def updateFigs(self):
        line = self.ser.readline() # read data from serial port, one line at a time
        self.data = [float(val) for val in line.split()] # split data to float numbers
        # the data read from the serial port should be 4 float numbers, otherwise neglect it.
        # the 4 float numbers are temperaure, humidity, voltage at reference electrode,
        # and voltage at pH electrode, respectively.
        line.decode("utf-8")
        if(len(self.data) == 4):
            self.temp_lcd.display(self.data[0])
            self.temp_plot.y = np.append(self.temp_plot.y, float(self.data[0]))
            self.temp_plot.y = np.delete(self.temp_plot.y, 0)
            self.temp_plot.li.set_ydata(self.temp_plot.y)
            self.temp_plot.axes.set_ylim(min(self.temp_plot.y)-1, max(self.temp_plot.y)+1)
            self.temp_plot.draw()

救命!

GUI 打开,但我还无法收集数据。

python python-3.x unicode python-unicode chemistry
1个回答
0
投票

在解析之前检查val

self.data = [float(val) for val in line.split() if val.isnumeric()]
© www.soinside.com 2019 - 2024. All rights reserved.