我正在使用Python 2.7并尝试将一个浮点值插入一个键。但是,所有值都插入为0.0。极性值插入为0.0而不是实际值。
代码段:
from textblob import TextBlob
import json
with open('new-webmd-answer.json') as data_file:
data = json.load(data_file, strict=False)
data_new = {}
lst = []
for d in data:
string = d["answerContent"]
blob = TextBlob(string)
#print blob
#print blob.sentiment
#print d["questionId"]
data_new['questionId'] = d["questionId"]
data_new['answerMemberId'] = d["answerMemberId"]
string1 = str(blob.sentiment.polarity)
print string1
data_new['polarity'] = string1
#print blob.sentiment.polarity
lst.append((data_new))
json_data = json.dumps(lst)
#print json_data
with open('polarity.json', 'w') as outfile:
json.dump(json_data, outfile)
答案 0 :(得分:0)
当前编写代码的方式,每次迭代都会覆盖字典。然后,您将该字典多次附加到列表中。
假设您的词典为dict = {"a" : 1}
,然后将其附加到列表
alist.append(dict)
alist
[{'a':1}]
然后更改dict的值dict{"a" : 0}
并再次将其附加到列表中alist.append(dict)
alist
[{'a':0},{'a':0}]
这是因为字典是可变的。有关可变对象和不可变对象的更完整概述,请参阅文档here
要实现预期输出,请在每次迭代data
lst = []
for d in data:
data_new = {} # makes a new dictionary with each iteration
string = d["answerContent"]
blob = TextBlob(string)
# print blob
# print blob.sentiment
# print d["questionId"]
data_new['questionId'] = d["questionId"]
data_new['answerMemberId'] = d["answerMemberId"]
string1 = str(blob.sentiment.polarity)
print string1
data_new['polarity'] = string1
# print blob.sentiment.polarity
lst.append((data_new))