1. 程式人生 > >文件內容轉換多層字典(適合新手理解)

文件內容轉換多層字典(適合新手理解)

返回 date usr 新手 return utf-8 輸入 pass pda

#!/usr/bin/env python
#-*- coding:UTF-8 -*-
flag = 0
return_flag = 0
f = open("file3.txt","r",encoding = "utf-8")
dict1 = {}
dict2 = {}
dict3 = {}
dict4 = {}
dict5 = {}
dict6 = {}
ZN = {}
MSK = {}
US = {}
info1 = {}
for i in f:
if "中國" in i:
list1 = i.strip().split(":")
list1[2] = list1[2].strip().split(",")
list1[4] = list1[4].strip().split(",")
list1[6] = list1[6].strip().split(",")
list1[8] = list1[8].strip().split(",")
dict1[list1[1]] = list1[2]
dict2[list1[3]] = list1[4]
dict3[list1[5]] = list1[6]
dict4[list1[7]] = list1[8]
ZN.update(dict2)
ZN.update(dict1)
ZN.update(dict3)
ZN.update(dict4)
if "美國" in i:
list2 = i.strip().split(":")
list2[2] = list2[2].strip().split(",")
dict5[list2[1]] = list2[2]
US.update(dict5)
if "俄羅斯" in i:
list3 = i.strip().split(":")
list3[2] = list3[2].strip().split(",")
dict6[list3[1]] = list3[2]
MSK.update(dict6)
else:
pass
f.close()
info1["中國"] = ZN
info1["美國"] = US
info1["俄羅斯"] = MSK

while flag == 0:

while return_flag == 0 and flag ==0:
for i in info1:
print(i)
choice1 = input("請選擇:")
return_flag = 1
break
while return_flag == 1 and flag == 0:
for i in info1[choice1]:
print(i)
choice2 = input("請輸入地名或按鍵選擇(r:返回上一級,q:退出)")
if choice2 == "q":
flag = 1
break
if choice2 == "r":
return_flag = 0
break
return_flag = 2
break
while return_flag == 2 and choice2 in info1[choice1] and flag ==0:
for a in info1[choice1][choice2]:
print(a)
choice3 = input("請輸入地名或按鍵選擇(r:返回上一級,q:退出)")
if choice3 == "q":
flag = 1
break
if choice3 == "r":
return_flag = 1
break
else:
print("歡迎來到%s!" % choice3)
flag = 1
break

文件存儲內容為:
‘‘‘
中國:北京:東城,西城,大興,房山:上海:靜安,普陀,浦東,金山:廣州:天河,越秀,海珠,白雲:香港:九龍,北區,大浦,沙田
美國:華盛頓:白宮
俄羅斯:莫斯科:沙皇
‘‘‘

文件內容轉換多層字典(適合新手理解)