我想通過語言分裂以下,嵌套的字典成不同的字典和創建一個新的JSON-檔案/字典為每種語言。
之后我想將它們合并在一起。
感謝任何建議如何繼續!
例子:
{
"All": {
"label_es_ES": "Todo",
"label_it_IT": "Tutto",
"label_en_EN": "All",
"label_fr_FR": "Tout"
},
"Searchprofile": {
"label_es_ES": "Perfil de búsqueda",
"label_it_IT": "Profilo di ricerca",
"label_en_EN": "Search profile",
"label_fr_FR": "Profil de recherche"
},
到目前為止我得到了什么:
import json
store_file = open( 'test.txt' , "w" )
with open('translations.json') as json_file:
data = json.load(json_file)
for label, translations in data.items():
for key in translations:
if key==('label_en_EN'):
json.dump(???, store_file)
.....'''
uj5u.com熱心網友回復:
用回圈瀏覽你的字典:
from pprint import pprint
data = {
"All": {
"label_es_ES": "Todo",
"label_it_IT": "Tutto",
"label_en_EN": "All",
"label_fr_FR": "Tout"
},
"Searchprofile": {
"label_es_ES": "Perfil de búsqueda",
"label_it_IT": "Profilo di ricerca",
"label_en_EN": "Search profile",
"label_fr_FR": "Profil de recherche"
}
}
new_data = dict()
for word,transl_dict in data.items():
for lbl, transl in transl_dict.items():
if not(lbl in new_data.keys()):
new_data[lbl] = dict()
new_data[lbl][word] = transl
pprint(new_data)
輸出:
{'label_en_EN': {'All': 'All', 'Searchprofile': 'Search profile'},
'label_es_ES': {'All': 'Todo', 'Searchprofile': 'Perfil de búsqueda'},
'label_fr_FR': {'All': 'Tout', 'Searchprofile': 'Profil de recherche'},
'label_it_IT': {'All': 'Tutto', 'Searchprofile': 'Profilo di ricerca'}}
您當然可以將 label_... 字典單獨轉儲到檔案中。
編輯:如果您已經知道有哪些標簽,那么輸出您的原始預期字典會更短:
labels = ["label_es_ES", "label_it_IT", "label_en_EN", "label_fr_FR"]
for label in labels:
label_dict = {x: {label: data[x][label]} for x in data}
pprint(label_dict)
# or dump directly to files;
with open(f"{label}.json", "w", encoding="utf-8") as f:
json.dump(label_dict, f, indent=4, ensure_ascii=False)
json 檔案以 utf-8 格式撰寫,以便您在 json 中看到特殊字符。稍后打開檔案時不要忘記指定編碼(utf-8)!
uj5u.com熱心網友回復:
from itertools import islice
def chunks(data, SIZE=10000):
it = iter(data)
for i in range(0, len(data), SIZE):
yield {k:data[k] for k in islice(it, SIZE)}
for item in chunks({i:i for i in range(10)}, 3):
print item
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/334126.html
上一篇:如何在DropDownField中設定狀態JSON?
下一篇:將元組作為鍵的字典轉換為JSON
