从Python中的文本文件中提取数据
问题描述:
我有一个文本文件,表示来自视频剪辑的运动矢量数据。从Python中的文本文件中提取数据
# pts=-26 frame_index=2 pict_type=P output_type=raw shape=3067x4
8 8 0 0
24 8 0 -1
40 8 0 0
...
8 24 0 0
24 24 3 1
40 24 0 0
...
8 40 0 0
24 40 0 0
40 40 0 0
# pts=-26 frame_index=3 pict_type=P output_type=raw shape=3067x4
8 8 0 1
24 8 0 0
40 8 0 0
...
8 24 0 0
24 24 5 -3
40 24 0 0
...
8 40 0 0
24 40 0 0
40 40 0 0
...
所以它是某种格子,前两位是x和y坐标,第三和第四是运动矢量的x和y值。
要进一步使用此数据,我需要提取x和y值对,其中至少有一个值与0不同,并将它们组织在列表中。
例如:
(0, -1, 2)
(3, 1, 2)
(0, 1, 3)
(5, 3, 3)
第三个数字是一个frame_index。
如果有人冷我的计划如何破解这个任务,我将不胜感激。从我应该开始。
答
这实际上很简单,因为只有一种类型的数据。 我们可以做到这一点,而不诉诸于例如常用表达。
忽略任何错误校验(难道我们真的看3067点帧2,或仅3065?的格式不正确?...行)会是这个样子
frame_data = {} # maps frame_idx -> list of (x, y, vx, vy)
for line in open('mydatafile.txt', 'r'):
if line.startswith('#'): # a header line
options = {key: value for key, value in
[token.split('=') for token in line[1:].split()]
}
curr_frame = int(options['frame_index'])
curr_data = []
frame_data[curr_frame] = curr_data
else: # Not a header line
x, y, vx, vy = map(int, line.split())
frame_data.append((x, y, vx, vy))
你知道有一本字典它将一个帧号映射到一个元组元素列表(x, y, vx, vy)
。
提取从词典中的新名单现在很容易:
result = []
for frame_number, data in frame_data.items():
for x, y, vx, vy in data:
if not (vx == 0 and vy == 0):
result.append((vx, vy, frame_number))
+0
非常感谢!我收到一个AttributeError:'dict'对象没有属性'append'。 所以改变 'frame_data.append((X,Y,VX,VY))' 到 'frame_data [curr_frame] .append((X,Y,VX,VY))' –
我假设的例子中'(5,3,3)'应该是'(5,-3,3)'? –
是的。该文件很大,所以我写了一个小例子来解释文件中的内容。 –