0

我有一个格式如下的文本文件:

hsa04012 [[['7039', '1956', '1398', '25'], ['7039', '1956', '1399', '25']], [['1839', '1956', '1398', '25'], ['1839', '1956', '1399', '25']], [['1399', '25']], [['1398', '25']], [['727738', '1956', '1398', '25'], ['727738', '1956', '1399', '25']], [['1956', '1398', '25'], ['1956', '1399', '25']], [['1950', '1956', '1398', '25'], ['1950', '1956', '1399', '25']], [['374', '1956', '1398', '25'], ['374', '1956', '1399', '25']], [['2069', '1956', '1398', '25'], ['2069', '1956', '1399', '25']], [['685', '1956', '1398', '25'], ['685', '1956', '1399', '25']]]
hsa02331...

如何将文件读入字典,其中键作为包含 hsa 的文本...,值作为括号内的数字 [作为列表]。

提前致谢

4

1 回答 1

4

我会使用str.splitand ast.literal_eval。这似乎最简单...

with open(datafile) as f:
    d = {}
    for line in f:
        key,value = line.split(None,1)
        d[key] = ast.literal_eval(value)

虽然,您也可以玩一些游戏json来获取列表。这些列表看起来是非常有效的 JSON 数组,因为它们被称为。

于 2012-11-13T02:20:26.223 回答