如何在文件中调用两个词典?

时间:2015-12-15 17:42:41

标签: python

来自集合导入OrderedDict 导入json

def read_classification_from_file(dict_file1,dict_file2):     打开(dict_file1,'r')作为f:         dict1 = json.load(f,object_pairs_hook = OrderedDict)     用open(dict_file2,'r')作为f:         data2 = json.load(f,object_pairs_hook = OrderedDict)

# Creates list of lists pairing each value in 
# dict1 with each value in dict2
return [[value1,value2] 
        for value1 in dict1.values() 
        for value2 in dict2.values()]

2 个答案:

答案 0 :(得分:0)

目前还不完全清楚你想要什么,如果我理解正确,那么完成你想要做的事情的理想方法却是采取不同的方法,但你想坚持这种方法,你可以使用eval()函数。您从.txt文件中读取字符串,但要使用该字符串,您需要将其作为参数传递给eval()函数,以便将其作为Python表达式进行解析和计算:

with open('example1.txt') as f:
    call = f.readline()

truth_dict = eval(call)

所以这可行:

from collections import namedtuple

def compute_confusion_matrix(file1, file2, pos_tag=True, neg_tag=False):
    TP=0
    FP=0
    TN=0
    FN=0
    with open(file1) as f:
        call = f.readline()
        truth_dict = eval(call)
    with open(file2) as f:
        call - f.readline()
        pred_dict = eval(call)

    for key,value in truth_dict.items():
        if truth_dict[key]==pred_dict[key] == neg_tag:
            TP +=1
        if pred_dict[key]==truth_dict[key] == pos_tag:
            FP +=1
        if truth_dict[key]==pred_dict[key] != neg_tag :
            TN +=1
        if truth_dict[key]==pred_dict[key] != pos_tag:
            FN +=1
    ConfMat = namedtuple('ConfMat', 'tp tn fp fn')

    p=ConfMat(TP, FP, TN, FN)
    return p

答案 1 :(得分:0)

如果您的数据是由其他来源创建或与其他来源共享,请使用json(仅使用双引号!)。可能希望使用OrderedDict来确保正确的顺序,或者更好的是,将数据重新组织为一个简单的值列表,因为密钥看起来并不重要:

from collections import OrderedDict
import json

def read_classification_from_file(dict_file1,dict_file2):
    with open(dict_file1,'r') as f:
        dict1 = json.load(f, object_pairs_hook=OrderedDict)
    with open(dict_file2,'r') as f:
        data2 = json.load(f, object_pairs_hook=OrderedDict)

    # Creates list of lists pairing each value in 
    # dict1 with each value in dict2
    return [[value1,value2] 
            for value1 in dict1.values() 
            for value2 in dict2.values()]