码迷,mamicode.com
首页 > 其他好文 > 详细

文件内容转换多层字典(适合新手理解)

时间:2017-08-12 00:33:54      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:coding   input   enc   ict   int   encoding   print   strip()   python   

#!/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

文件存储内容为:
‘‘‘
中国:北京:东城,西城,大兴,房山:上海:静安,普陀,浦东,金山:广州:天河,越秀,海珠,白云:香港:九龙,北区,大浦,沙田
美国:华盛顿:白宫
俄罗斯:莫斯科:沙皇
‘‘‘

文件内容转换多层字典(适合新手理解)

标签:coding   input   enc   ict   int   encoding   print   strip()   python   

原文地址:http://www.cnblogs.com/lzj-HH/p/7348424.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!