Python 如何调用文件中的两个词典?
从集合导入订单 导入json 从目录文件(目录文件1,目录文件2)读取目录分类: 将open(dict_file1,'r')作为f: dict1=json.load(f,对象\u对\u钩子=OrderedDict) 将open(dict_file2,'r')作为f: data2=json.load(f,object\u pairs\u hook=OrderedDict)Python 如何调用文件中的两个词典?,python,Python,从集合导入订单 导入json 从目录文件(目录文件1,目录文件2)读取目录分类: 将open(dict_file1,'r')作为f: dict1=json.load(f,对象\u对\u钩子=OrderedDict) 将open(dict_file2,'r')作为f: data2=json.load(f,object\u pairs\u hook=OrderedDict) 现在还不完全清楚您想要什么,如果我对您的理解正确,那么实现您想要做的事情的理想方法是采用不同的方法,但如果您想坚持这种方法,可
现在还不完全清楚您想要什么,如果我对您的理解正确,那么实现您想要做的事情的理想方法是采用不同的方法,但如果您想坚持这种方法,可以使用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
如果您的数据由其他源创建或与其他源共享,请使用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()]
你能澄清一下你的帖子吗?你想做什么还不清楚。第一个函数在你提供真值字典和预测字典时起作用,所以我想用另一种方式使用它,在read\u classification\u from\u file()中打开example1.txt和example2.txt,然后我想计算混淆矩阵(真值字典,预测字典,pos\u tag=True,neg\u tag=False):使用从文件()读取的分类中返回的字典:或者如果我可以在计算混淆矩阵中打开两个文件(真值、预测混淆矩阵、pos标签=真值、负标签=假值):如果可能的话,我可以在计算混淆矩阵中打开两个字典(真值、预测混淆矩阵、pos标签=真值、负标签=假值):不使用从文件()读取的分类:???您不是从.txt文件“打开词典”。你在读字符串,而不是字典。您需要将它们编入字典,通过使用eval函数,您可以像对待Python表达式一样对待这些字符串,并像在“测试”中一样创建字典。否则,所有的都是strings.ok,但是.txt文件已经是字典了,所以我想在compute\u conflusion\u矩阵中读取它们,这样我可以通过打印来测试函数。txt文件不是字典。它们是弦。要将对象保存到文件中,您需要使用对象序列化和“pickle”模块:抱歉,是的,我刚刚意识到了,谢谢,但是您可以读取compute\u composition\u矩阵中的两个.txt文件(truth\u dict,pred\u dict,pos\u tag=True,neg\u tag=False)并通过在参数中提供.txt文件来打印它吗
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()]