【问题标题】:More Efficient Conversion of Archived Python Dict to JSON归档 Python Dict 到 JSON 的更高效转换
【发布时间】:2012-06-14 22:42:50
【问题描述】:

我有很多 python dict 格式的存档数据,我正在努力将它们转换为 json。如果可以的话,我有兴趣加快这个过程,并且想知道是否有人有任何建议。目前我:

  1. “在多个文件中”接收 gzip 压缩数据
  2. 逐行阅读
  3. 用 ast 做一个 literal_eval
  4. 使用 json 转储来创建所需的 json 字符串
  5. 查询线路日期
  6. 打开一个以检测到的日期命名的附加文件
  7. 将字符串写入文件
  8. 重启整个进程

这是我当前的工作代码:

import gzip
import ast
import json
import glob
import fileinput
from dateutil import parser

line = []

filestobeanalyzed = glob.glob('./data/*.json.gz')

for fileName in filestobeanalyzed:
        inputfilename = fileName
        print inputfilename # to keep track of where I'm at
        for line in fileinput.input(inputfilename, openhook=fileinput.hook_compressed):
                line = line.strip();
                if not line: continue
                try:
                        line = ast.literal_eval(line)
                        line = json.dumps(line)
                except:
                        continue
                date = json.loads(line).get('created_at')
                    if not date: continue
                date_converted = parser.parse(date).strftime('%Y%m%d')
                outputfilename = gzip.open(date_converted, "a")
                outputfilename.write(line)
                outputfilename.write("\n")

outputfilename.close()

必须有更有效的方法来做到这一点,我只是没有看到。有人有什么建议吗?

【问题讨论】:

    标签: python json gzip converter abstract-syntax-tree


    【解决方案1】:

    首先使用http://packages.python.org/line_profiler/ 对其进行分析,它将逐行为您提供时间,您也可以尝试对其进行多线程处理,使用多处理池并将文件列表映射到您的函数。

    虽然我觉得 IO 可能是个问题,但这又取决于文件的大小。

    # Assuming you have a large dictionary across a multi-part gzip files.
    def files_to_be_analyzed(files):
        lines = ast.literal_eval("".join([gzip.open(file).read() for file in files]))
        date = lines['created_at']
        date_converted = parser.parse(date).strftime('%Y%m%d')
        output_file = gzip.open(date_converted, "a")
        output_file.write(lines + "\n")
        output_file.close()
    

    我仍然不太确定您要达到什么目标,但请尽量少读和写,因为 IO 是一个杀手。如果您需要在多个目录上工作,请查看多线程,如下所示。

    import gzip
    import ast
    import json
    import glob
    import fileinput
    from dateutil import parser
    from multiprocessing import Pool
    
    # Assuming you have a large dictionary across a multi-part gzip files.
    def files_to_be_analyzed(files):
        lines = ast.literal_eval("".join([gzip.open(file).read() for file in files]))
        date = lines['created_at']
        date_converted = parser.parse(date).strftime('%Y%m%d')
        output_file = gzip.open(date_converted, "a")
        output_file.write(lines + "\n")
        output_file.close()
    
    if __name__ == '__main__':
        pool = Pool(processes = 5) # Or what ever number of cores you have
        directories = ['/path/to/this/dire', '/path/to/another/dir']
        pool.map(files_to_be_analyzed, [glob.glob(path) for path in directories])
        pools.close()
        pools.join()
    

    【讨论】:

    • 我的目标是通过多种格式结构的管理来维护历史数据的存档:即:python dict、json 等。这使我可以使用其他语言的其他工具,这些工具只能阅读特定格式。我其实对line_profiler不熟悉,这很有用,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    相关资源
    最近更新 更多