Python 3.x 如何在Python中获取字典值
我正在使用python字典和ntlk进行一些评论。我有一个简单的评论文件(Python 3.x 如何在Python中获取字典值,python-3.x,dictionary,nltk,Python 3.x,Dictionary,Nltk,我正在使用python字典和ntlk进行一些评论。我有一个简单的评论文件(txt)。在字典中所有dict.txt。我所有的词(否定词和肯定词)都有极性和价值 all_dict.txt如下所示 "acceptable":("positive",1),"good":("positive",1),"shame":("negative",2),"bad":("negative",4),... 我想知道如何从字典中获取极性和每个单词的数值,以便获得如下输出: "acceptable_positive":
txt
)。在字典中所有dict.txt
。我所有的词(否定词和肯定词)都有极性和价值
all_dict.txt
如下所示
"acceptable":("positive",1),"good":("positive",1),"shame":("negative",2),"bad":("negative",4),...
我想知道如何从字典中获取极性和每个单词的数值,以便获得如下输出:
"acceptable_positive":1,"good_positive":1,"shame_negative":2,"bad_negative":4
我尝试了dict.get()
,dict.values
,但没有得到我想要的。是否有自动获取键和值的方法
我尝试使用我的代码:
f_all_dict=open('all_dict.txt','r',encoding='utf-8').read()
f = eval(f_all_dict)
result_all = {}
for word in f.items():
suffix, pol=result_all[word] #pol->polarity
result_all[word + "_" + suffix] = pol
但是,如果输入文件中不存在该单词,我会得到KeyError
(查看)
感谢您的帮助首先,
dict.items()
返回一个dictitem
对象,该对象包含键和值的元组,当您想将其作为键传递到字典时,它会引发一个键错误
suffix, pol=result_all[word]
其次,最好使用with
语句来处理文件等外部对象。并使用ast.literal\u eval()
评估字典。您还可以使用dict理解中的一次性变量解包:-),访问您的值项
from ast import literal_eval
with open('all_dict.txt','r',encoding='utf-8') as f_all_dict:
dictionary = literal_eval(f_all_dict.read().strip())
result_all = {"{}_{}".format(word, suffix): pol for word, (suffix, pol) in dictionary.items()}
修改后,我的代码如下所示。我没有对语句使用
,它工作得很好
f_all_dict=open('all_dict.txt','r',encoding='utf-8').read()
f = literal_eval(f_all_dict)
result_all = {}
for word in f.items():
result_all = {"{}_{}".format(word, suffix): pol * tokens.count(word) for word, (suffix, pol) in f.items()}
print(result_all)
“return a tuple of key and value”虽然不是真的,但它返回了一个可以迭代的dict_items
实例。@MarkusMeskanen的确,我错过了Python 3.x标记:-)它有帮助,我使用了literal_eval()
并用它修改了我的代码。我得到了我想要的结果。谢谢:)