我是 Python 的新手,我需要你的帮助。 我制作了一个小程序,它从串行端口读取模拟信号并将其转储到文件中。然而,即使读取非常精确,有时它也会将不必要的/未确定的字符转储到文件中:
这是一个 500 行文件的转储;检查第二个值: 466 +466 466 466
所以,基本上问题是我不知道如何从读数中过滤此输入。我一直在阅读正则表达式部分的文档,但我无法正确处理/操纵结果。如您所见,“purifystring”函数非常不完整...
import serial
import re
#this is the pain...
def purifystring(string):
regobj = re.match("^([0-9]+)$")
result = regobj.find(string)
#start monitoring on ttyACM0 at 9600 baudrate
ser = serial.Serial('/dev/ttyACM0', 9600)
#the dump file
filename = 'output.txt'
#save data to file
f = open(filename, 'w')
counter = 0;
while counter < 500:
analogvalue = ser.readline()
#need to clean the input before writing to file...
#purifystring(analogvalue)
#output to console (debug)
f.write(analogvalue)
counter += 1
f.close()
print 'Written '+ str(counter)+' lines to '+filename;
因此,尽管这可能不是最好的方法,但我乐于接受建议。我正在尝试使我的输出文件的每行值介于 0 到 1023 之间。我从读取序列中获得的数据是一个类似于“812\n”的字符串。
提前致谢!
请您参考如下方法:
要以简单的方式完成工作(即没有正则表达式;))试试这个:
def purifystring(string_to_analyze): # string is a really bad variable name as it is a python module's name
return "".join(digit for digit in string_to_analyze if digit.isdigit())
这样,您将仅过滤接收到的数据的数字。 ( isdigit() )
