2 回答

TA貢獻1847條經驗 獲得超7個贊
json 模塊可用于將 python 字典存儲到文件中,然后加載文件并在將其寫入文件之前將其解析為相同的數(shù)據類型。
d = {}
with open('filtered.txt') as input:
for line in input:
key, value = line.strip().split("():")
key = "{}()".format(key)
d[key] = value
print(d)
# It would be better and easy if you write the data to the file using json module
import json
with open('data.txt', 'w') as json_file:
json.dump(d, json_file)
# Later you can read the file using the json module itself
with open('data.txt') as f:
# this data would be a dicitonay which can be easily managed.
data = json.load(f)

TA貢獻1850條經驗 獲得超11個贊
使用ast.literal_eval您可以將字符串列表轉換為list
from collections import defaultdict
import ast
with open('tst.txt') as fp:
d = defaultdict(list)
for line in fp:
k, v = line[: line.index('):') + 1], ast.literal_eval(line[line.index(':[') + 1:])
d[k] += v
print(dict(d))
輸出:
{
M:org.apache.mahout.common.RandomUtilsTest:testHashDoubl : ['(O)java.lang.Double:<init>(double)', '(M)java.lang.Double:hashCode()', '(S)org.apache.mahout.common.RandomUtils:hashDouble(double)', '(S)org.apache.mahout.common.RandomUtilsTest:assertEquals(long,long)', '(O)java.lang.Double:<init>(double)']
M:org.apache.mahout.common.RandomUtilsTest:testHashFloa : ['(M)java.util.Random:nextLong()', '(M)java.util.Random:nextLong()', '(M)java.util.Random:nextLong()', '(S)org.apache.mahout.common.RandomUtilsTest:assertEquals(java.lang.String,long,long)']
M:org.apache.mahout.math.AbstractVectorTest:testAssignBinaryFunctio : ['(I)org.apache.mahout.math.Vector:assign(org.apache.mahout.math.Vector,org.apache.mahout.math.function.DoubleDoubleFunction)', '(O)java.lang.StringBuilder:<init>()', '(I)org.apache.mahout.math.Vector:getQuick(int)', '(S)org.apache.mahout.math.AbstractVectorTest:assertEquals(java.lang.String,double,double,double)']
M:org.apache.mahout.math.AbstractVectorTest:testAssignBinaryFunction : ['(S)org.apache.mahout.math.function.Functions:plus(double)', '(I)org.apache.mahout.math.Vector:assign(org.apache.mahout.math.function.DoubleFunction)', '(S)org.apache.mahout.math.AbstractVectorTest:assertEquals(java.lang.String,double,double,double)']
}
添加回答
舉報