Python中从文本文件中提取数据

时间:2016-03-08 15:37:51

标签: python text-files data-extraction

我有一个文本文件,用于表示视频剪辑中的运动矢量数据。

# 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。

如果有人感冒帮助我完成破解这项任务的计划,我会非常感激。从我应该开始。

1 个答案:

答案 0 :(得分:1)

这实际上非常简单,因为只有一种类型的数据。 我们可以这样做,而无需诉诸于正则表达式。

忽略任何错误检查(我们实际上是否读取了第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))