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

Python 以适当的格式解析此类文件,python,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

我想在[{},{}]中解析这个文件

每个散列都是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]

除非您的文件是标准格式的ex: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\u-value\u对以某种方式仅包含1个条目,则可能会遇到潜在的问题。但以你的例子来说,这很好