為了有效地解析固定寬度文件,可以考慮利用Python的struct模組。此方法利用 C 來提高速度,如下例所示:
<code class="python">import struct fieldwidths = (2, -10, 24) fmtstring = ' '.join('{}{}'.format(abs(fw), 'x' if fw <p>或者,可以採用字串切片。為了提高效率,可以考慮定義一個在運行時編譯切片的 lambda 函數,如下面的最佳化版本所示:</p> <pre class="brush:php;toolbar:false"><code class="python">def make_parser(fieldwidths): cuts = tuple(cut for cut in accumulate(abs(fw) for fw in fieldwidths)) pads = tuple(fw </code>
以上是如何在Python中優化固定寬度檔案解析?的詳細內容。更多資訊請關注PHP中文網其他相關文章!