Python 如何忽略非浮点值
我有一个USB温度记录器,每30秒上传到Cosm。我遇到的问题是,每5分钟,当我运行命令时,它会报告一个文本错误,而不是一个数字 因此,我试图找到一种方法,让它进入循环,直到它收到一个数字,或者忽略文本并恢复脚本(否则它会退出并出错) 我非常不雅观的解决方案是这样做:Python 如何忽略非浮点值,python,ignore,Python,Ignore,我有一个USB温度记录器,每30秒上传到Cosm。我遇到的问题是,每5分钟,当我运行命令时,它会报告一个文本错误,而不是一个数字 因此,我试图找到一种方法,让它进入循环,直到它收到一个数字,或者忽略文本并恢复脚本(否则它会退出并出错) 我非常不雅观的解决方案是这样做: # convert regular error message to number if temp_C == "temporarily": # "temporarily" is used as it happens t
# convert regular error message to number
if temp_C == "temporarily": # "temporarily" is used as it happens to be the 4th word in the error message
temp_C = 0.0
目前的代码体系是:
while True:
# read data from temper usb sensor
sensor_reading=commands.getoutput('pcsensor')
#extract single temperature reading from the sensor
data=sensor_reading.split(' ') #Split the string and define temperature
temp_only=str(data[4]) #knocks out celcius reading from line
temp=temp_only.rstrip('C') #Removes the character "C" from the string to allow for plotting
# calibrate temperature reading
temp_C = temp
# convert regular error message to number
if temp_C == "temporarily":
temp_C = 0.0
# convert value to float
temp_C = float(temp_C)
# check to see if non-float
check = isinstance(temp_C, float)
#write out 0.0 as a null value if non-float
if check == True:
temp_C = temp_C
else:
temp_C = 0.0
在Python中,请求原谅通常比请求允许更容易()。当遇到
ValueError
时,继续
到下一次迭代:
try:
temp_C = float(temp_C)
except ValueError:
continue # skips to next iteration
或者更紧凑(整合大部分功能):
只需捕获转换失败时发生的
ValueError
异常:
try:
temp_C = float(temp)
except ValueError:
temp_C = 0.0
这会将非浮点值转换为“0.0”(看起来会)。我希望能够跳过错误,而不是像以前那样报告0.0。啊。如果要完全跳过它们,请将
continue
放在except子句中。编辑答案来做这个。非常感谢,这正是我要找的!谢谢,这要整洁得多-但是,我希望避免将其替换为零,只需跳过代码的运行(当我绘制这些值时,一直下降到零看起来很混乱)。您可以跳过值,如上图所示。另一种选择是重复使用以前的测量值。
try:
temp_C = float(temp)
except ValueError:
temp_C = 0.0