验证从传感器接收的变量

时间:2014-07-18 21:02:02

标签: python variables multiple-conditions

我有一个输出几个值的设备,通常如下所示:

-1.6410,0.5390,0.5570
-1.6160,0.3860,0.5620
-1.4890,-0.0760,0.5260
-1.4120,-0.1740,0.5290
-1.2920,-0.2160,0.6110
-1.2520,-0.2510,0.6450
-1.2530,-0.2270,0.6330
-1.2670,-0.2220,0.6530
-1.2350,-0.2250,0.7170
-1.4470,-0.3840,0.2400
-1.2670,-0.7480,0.0630
-1.0690,-0.9340,-0.1400
-0.9440,-1.0000,-0.2440

这三个数字可以是任意长度,可以是正数或负数。有没有办法(在Python中)检查是否返回了有效数字而不是文本字符串(如“CHECKSUM ERROR”之类的东西)?我不知道可能收到哪些文本错误,所以我想尝试验证收到的数字。这可能吗?

我曾为每个变量考虑过一个简单的IF语句,但这看起来很笨拙。例如:

if (value1 > -9999) and (value1 < 9999):
...

我必须为三个值中的每个值执行此操作。有更简单的方法吗?

2 个答案:

答案 0 :(得分:2)

您可以通过正则表达式传递每一行

import re

valid_pattern = re.compile('-?\d\.\d+,-?\d\.\d+,-?\d\.\d+')

for line in lines:
    if valid_pattern.match(line):
        x,y,z = map(float(line.split(","))
    else:
        pass #ignore the line, maybe print a warning whatever

答案 1 :(得分:1)

解决方案可以很简单:尝试获取值,如果失败(抛出一些预测的异常),则将其作为无效条目并忽略它。

lines = """
-1.6410,0.5390,0.5570
-1.6160,0.3860,0.5620
-1.4890,-0.0760,0.5260
-1.4120,-0.1740,0.5290
-1.2920,-0.2160,0.6110
-1.2520,-0.2510,0.6450
-1.2530,-0.2270,0.6330
-1.2670,-0.2220,0.6530
-1.2350,-0.2250,0.7170
-1.4470,-0.3840,0.2400
-1.2670,-0.7480,0.0630
BAD GUY WAS HERE
-1.0690,-0.9340,-0.1400
-0.9440,-1.0000,-0.2440
"""

for line in lines.strip().split("\n"):
    try:
        x, y, z = map(float, line.split(","))
        # continue processing here
        print x, y, z
    except ValueError:
        print "I do not like this line", line
        continue