我有一个文本文件,表示来自视频剪辑的运动矢量数据。
# 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 值。
为了进一步使用这些数据,我需要提取至少有一个值不同于 0 的 x 和 y 值对,并将它们组织在列表中。
例如:
(0, -1, 2)
(3, 1, 2)
(0, 1, 3)
(5, 3, 3)
第三个数字是 frame_index。
如果有人能帮助我制定如何破解此任务的计划,我将不胜感激。从我应该做的开始。
最佳答案
这实际上很简单,因为只有一种类型的数据。 我们可以做到这一点而无需诉诸例如正则表达式。
忽略任何错误检查(我们实际上是为第 2 帧读取了 3067 个点,还是只读取了 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))
关于python - 从Python中的文本文件中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35871625/