2016-11-19 17 views
0

開源軟件SOX是一個命令行界面工具,它可以處理音頻文件。它有一個stat函數,用於返回與音頻文件相關的數據。這些數據以字符串形式返回 - 這是一個不易使用的字符串。從Python的SOX字符串輸出中獲取字典中的可用數據

SOX返回的字符串示例如下。

\ 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部門\ n文件大小:10.6米\ n位速率:2.82M \編碼NSample個:16位有符號整數PCM \ n」個

和...

樣品閱讀:5292001 \ nLength(秒):30.000006 \ n縮放比例:2147483647.0 \ n最大幅度:0.705475 \ n最小幅度:-0.705475 \ n中線幅度:0.000000 \ n平均值:0.449045 \ n平均幅度:0.000153 \ nRMS幅度:0.498788 \ n最大增量:1.410950 \ n最小增量:0.000000 \ 0.571030 \ nRMS delta:0.704606 \ nRough頻率:3965 9 \ n音量調整:1.417 \ n \ n嘗試:-t raw -e mu-law -b 8'

一個值可能有的字符數可能會從一個文件改變到另一個文件,而某些文件實際上會丟失某些值共。

如何從這些字符串獲取簡單的值字典?

回答

1

你可以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'} 
+1

哇。完善。非常感謝。 – user3535074

相關問題