我想从一个模拟来自COM端口流的数据的文件中读取。
该文件有7个列号,其中包含XYZ轴上的陀螺仪和加速度计的样本,例如:
0.02775096893310547 0.0 0.0 0.0 -0.021 0.001 1.018
0.043855905532836914 0.017453292519943295 0.3490658503988659 -3.490658503988659 -0.23800000000000002 -0.165 0.972
0.1978168487548828 0.8377580409572782 0.6283185307179586 -6.789330790257942 -0.28400000000000003 -0.138 0.97
0.29178690910339355 0.10471975511965978 1.2566370614359172 -3.735004599267865 -0.272 -0.168 0.961
0.36679887771606445 0.0 1.3264502315156905 -5.98647933434055 -0.243 -0.20700000000000002 0.967
0.4776029586791992 0.8901179185171081 1.9722220547535925 -9.023352232810684 -0.272 -0.241 0.9430000000000001我的近似函数由两个函数组成:
import pandas as pd
myfile = pd.read_csv("bimu_gyro_accel.dat", header=None, delimiter=r"\s+")
def get_the_gyro(row,file=myfile):
""" Gets XYZ gyroscope axis from 'file' variableName and row number
Data units is radians
The result is a dictionary x,y,z keys, e.g., dic['x']
"""
g_xyz = file.iloc[row-1,1:4]
g_xyz_dict = g_xyz.to_dict()
g_xyz_dict['x'] = g_xyz_dict.pop(1)
g_xyz_dict['y'] = g_xyz_dict.pop(2)
g_xyz_dict['z'] = g_xyz_dict.pop(3)
return g_xyz_dict
def get_the_accel(row,file=myfile):
""" Gets XYZ acceleromenter axis from 'file' variableName and row number
Data units is 'g, ~9.8m/s^2'
The result is a dictionary x,y,z keys, e.g., dic['x']
"""
a_xyz = file.iloc[row-1,4:7]
a_xyz_dict = a_xyz.to_dict()
a_xyz_dict['x'] = a_xyz_dict.pop(4)
a_xyz_dict['y'] = a_xyz_dict.pop(5)
a_xyz_dict['z'] = a_xyz_dict.pop(6)
return a_xyz_dict这是一个脚本read_gyro_accel.py。
下面是一个使用示例:
>>> from read_gyro_accel import get_the_gyro, get_the_accel
>>> get_the_gyro(3)
{'x': 0.8377580409572782, 'y': 0.6283185307179586, 'z': -6.789330790257942}
>>> get_the_accel(3)
{'x': -0.28400000000000003, 'y': -0.138, 'z': 0.97}
>>>我必须传递行号才能获得数据。我的问题是,是否有任何方法可以在不传递任何输入参数的情况下调用函数get_the_gyro和get_the_accel,并获得下一个陀螺仪和加速度计XYZ数据,并按顺序获得所有行的数据。
发布于 2020-04-28 17:50:32
我错过了什么吗?!为什么不在函数中将row声明为默认参数?例如: get_the_gyro(row=3,file=myfile)。就叫它get_the_gyro()吧!??
发布于 2020-04-28 18:42:25
好了,现在更好地解释了,我们有3种不同的方法来解决这个问题。1.使用生成器-大文件的惰性方法2.使用迭代器-我不会给出一个例子3.使用文件对象。
第一种方法(适用于大文件,并且您希望逐行处理数据):
def read_gyro_line(file=myfile):
while True:
data = file.readline()
if not data:
break
#do some work on data and return the data as dict
yield data
# below how we call the generator func
with open('file_for_example.txt') as fp:
for data_line in read_gyro_line(fp):
do_work_on(data_line)第三种方法,使用python标准文件方法。请参见:
def process_data(data_line):
#do some work on data_line
with open('file_for_example.txt') as fp:
for line in fp:
process_data(line)https://stackoverflow.com/questions/61476999
复制相似问题