我有多個文本文件,裡面有這個(具有不同的值):
{"abandon": {"R1F2V0CQAYJOZZ": 2, "R3NUFWQ9SPGVJO": 1}, "abduct": {"R1F2V0CQAYJOZZ": 1, "R3376OQSHCTV1A": 1, "R14BW4EQZNVKKG": 1, "R233CMES8RCOCU": 1},
如果我在線格式化它會變成這樣:
"abandon":{
"R1F2V0CQAYJOZZ":2,
"R3NUFWQ9SPGVJO":1
},
"abduct":{
"R1F2V0CQAYJOZZ":1,
"R3376OQSHCTV1A":1,
"R14BW4EQZNVKKG":1,
"R233CMES8RCOCU":1
},
這個 JSON 的意思是:
"word":{
"Document name":"value"
},
但是在不同的文件中有重複的單詞。我想要做的是:讀取所有文件並將所有內容存儲在一本字典中,但是:
編輯:
所以想像一下這兩個文件:
File1.txt = {"abandon": {"doc1": 2, "doc2": 1}, "abduct": {"doc1": 1, "doc2": 1, "doc8": 1},
File1.txt = {"abandon": {"doc1": 1, "doc3": 1}, "abduct": {"doc5": 1, "doc8": 1},
我希望我的字典以這樣的方式結束:
{"abandon": {"doc1": 3, "doc2": 1, "doc3": 1}, "abduct": {"doc1": 1, "doc2": 1, "doc5": 1, "doc8": 2},
EDIT2:它也可以是嵌套列表
IIUC,嘗試:
import os
import json
files = [f for f in os.listdir() if f.endswith(".txt")]
result = dict()
for file in files:
d = json.load(open(file))
for word in d:
if word not in result:
result[word] = dict()
for doc in d[word]:
if doc not in result[word]:
result[word][doc] = d[word][doc]
else:
result[word][doc] += d[word][doc]
>>> result
{'abandon': {'doc1': 3, 'doc2': 1, 'doc3': 1},
'abduct': {'doc1': 1, 'doc2': 1, 'doc8': 2, 'doc5': 1}}
輸入文件:
文件1.txt:
{"abandon": {"doc1": 2, "doc2": 1}, "abduct": {"doc1": 1, "doc2": 1, "doc8": 1}}
文件2.txt:
{"abandon": {"doc1": 1, "doc3": 1}, "abduct": {"doc5": 1, "doc8": 1}}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句