以适当的格式解析此类文件

时间:2014-07-04 09:14:38

标签: python

我想在[{},{}]

中解析此文件

每个哈希都是STREAM标记中的部分

有没有图书馆可以做到这一点?感谢

[STREAM]
index=0
codec_name=h264
codec_long_name=H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
has_b_frames=2
sample_aspect_ratio=0:1
display_aspect_ratio=0:1
pix_fmt=yuv420p
level=11
timecode=N/A
id=N/A
r_frame_rate=15000/1001
avg_frame_rate=15000/1001
time_base=1/15000
start_pts=0
start_time=0.000000
duration_ts=76076
duration=5.071733
[/STREAM]
[STREAM]
index=1
codec_name=aac
codec_long_name=AAC (Advanced Audio Coding)
channels=1
[/STREAM]

1 个答案:

答案 0 :(得分:2)

除非您的文件是标准格式(例如:csv),否则可能没有一个库已经知道如何解析它。然而,这种简单的格式并不难写出解析循环。我将你的例子保存到streams.txt并运行了这个

import pprint

streams = []
stream = {}
with open("streams.txt", "r") as streams_file:
    for line in streams_file:
        # Remove whitespace and newline character
        line = line.strip()
        if line == "[STREAM]":
            # Start of new stream
            stream = {}
        elif line == "[/STREAM]":
            # End of stream, add it to streams list
            streams.append(stream)
        else:
            # Item of stream
            key_value_pair = line.split("=")
            if key_value_pair:
                stream[key_value_pair[0]] = key_value_pair[1]

pprint.pprint(streams)

提供了此输出

[{'avg_frame_rate': '15000/1001',
  'codec_long_name': 'H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10',
  'codec_name': 'h264',
  'display_aspect_ratio': '0:1',
  'duration': '5.071733',
  'duration_ts': '76076',
  'has_b_frames': '2',
  'id': 'N/A',
  'index': '0',
  'level': '11',
  'pix_fmt': 'yuv420p',
  'r_frame_rate': '15000/1001',
  'sample_aspect_ratio': '0:1',
  'start_pts': '0',
  'start_time': '0.000000',
  'time_base': '1/15000',
  'timecode': 'N/A'},
 {'channels': '1',
  'codec_long_name': 'AAC (Advanced Audio Coding)',
  'codec_name': 'aac',
  'index': '1'}]

如果文件中存在错误信息,如果等号多出一行,或者key_value_pair以某种方式仅以1个条目结束,则可能会遇到潜在问题。但是以你的例子来说这很好。

相关问题