你可以split
上'\n'
再喂上':'
對到dict
構造函數通過拆分:
鑑於你的第二個示例字符串:
>>> dict(r.strip().split(':', 1) for r in s.split('\n') if r)
:
>>> s = """Samples read: 5292001\nLength (seconds): 30.000006\nScaled by: 2147483647.0\nMaximum amplitude: 0.705475\nMinimum amplitude: -0.705475\nMidline amplitude: 0.000000\nMean norm: 0.449045\nMean amplitude: 0.000153\nRMS amplitude: 0.498788\nMaximum delta: 1.410950\nMinimum delta: 0.000000\nMean delta: 0.571030\nRMS delta: 0.704606\nRough frequency: 39659\nVolume adjustment: 1.417\n\nTry: -t raw -e mu-law -b 8 '"""
字典可以通過以下方式創建
其中if r
需要注意濾除空行和在拆分1
照顧執行只有一個拆分(所以字符串像Duration
有很多":"
不會分裂多次)。
這產生了:
{'Length (seconds)': ' 30.000006',
'Maximum amplitude': ' 0.705475',
'Maximum delta': ' 1.410950',
'Mean amplitude': ' 0.000153',
'Mean delta': ' 0.571030',
'Mean norm': ' 0.449045',
'Midline amplitude': ' 0.000000',
'Minimum amplitude': ' -0.705475',
'Minimum delta': ' 0.000000',
'RMS amplitude': ' 0.498788',
'RMS delta': ' 0.704606',
'Rough frequency': ' 39659',
'Samples read': ' 5292001',
'Scaled by': ' 2147483647.0',
'Try': " -t raw -e mu-law -b 8 '",
'Volume adjustment': ' 1.417'}
類似地,與第一樣本串:
>>> s = """\nInput File : 'E:\\path\\to\\file\\filename.wav'\nChannels : 1\nSample Rate : 176400\nPrecision : 16-bit\nDuration : 00:00:30.00 = 5292001 samples ~ 2250 CDDA sectors\nFile Size : 10.6M\nBit Rate : 2.82M\nSample Encoding: 16-bit Signed Integer PCM\n"""
>>> dict(r.strip().split(':', 1) for r in s.strip().split('\n') if r)
{'Bit Rate ': ' 2.82M',
'Channels ': ' 1',
'Duration ': ' 00:00:30.00 = 5292001 samples ~ 2250 CDDA sectors',
'File Size ': ' 10.6M',
'Input File ': " 'E:\\path\\to\\file\\filename.wav'",
'Precision ': ' 16-bit',
'Sample Encoding': ' 16-bit Signed Integer PCM',
'Sample Rate ': ' 176400'}
哇。完善。非常感謝。 – user3535074