python - 从Python中的文本文件中提取数据

标签 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 值。

为了进一步使用这些数据,我需要提取至少有一个值不同于 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/

相关文章:

python - 如何在Python中使用正则表达式查找和计算文本文件中的每一行?

python - 将字典数据附加到 python 列表中时输出更改

python - python中从下一个时间值中减去上一个时间值

python - azure-keyvault-secrets python 包中的 SecretClient 类引发意外错误

python - boost Python 哈希

python - 在 Python 中将命名空间放入不同的 XML 标签中

Python - 唯一确定元素源自哪个文本文件

python - 使用reduce组合不同数据帧之间多列的 bool 运算

vba - 从文本文件中读取数据并分隔

pandas - 从 ERA5 再分析中提取移动船舶的时间和空间变量