Python实现三层菜单操作

#!/usr/bin/env python3
# encoding:utf-8
# __author__: chenwei
# date: 2017-05-25
# blog: http://www.cnblogs.com/weiandlu/

'''json数据文件格式如下:
{
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '网易':{},
                'google':{}
            },
            '中关村':{
                '爱奇艺':{},
                '汽车之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '高教园':{},
                '北航':{},
            },
            '天通苑':{},
            '回龙观':{},
        },
        '朝阳':{},
        '东城':{},
    },
    '上海':{
        '闵行':{
            "人民广场":{
                '炸鸡店':{}
            }
        },
        '闸北':{
            '火车战':{
                '携程':{}
            }
        },
        '浦东':{},
    },
    '山东':{},
}
'''
import json
def read_data():
    with open("administrative_division.json","r",encoding="utf8") as f_read:
        data=json.load(f_read)
        return data

def write_data(data):
    with open("administrative_division.json","w",encoding="utf8") as f_write:
        json.dump(data,f_write)

data = read_data()
current_layer = data
last_layer = [] #在菜单层层深入是记录上一层菜单
num_to_menu = {} #将城市列表前面打印的序号与城市名称进行对应
while True:
    print("欢迎使用三级菜单系统".center(50,"#"))
    for i,v in enumerate(current_layer,1):
        print("%s\t%s\t" % (i,v),end='')
        num_to_menu[i] = v
    print()
    choice=input("请选择对应选项前的字母:\na:添加,d:删除,m:修改,b:返回,q:退出:").strip()
    if choice.isdigit() and int(choice) in num_to_menu:
        last_layer.append(current_layer)
        current_layer = current_layer[num_to_menu[int(choice)]]
        write_data(data)
    elif choice == 'a':
        city=input("请输入城市名称!:").strip()
        if current_layer.get(city):
            print("该城市已存在")
        else:
            current_layer.update({city:{}})
        write_data(data)
    elif choice == 'd':
        city_num=int(input("请输入删除城市序号!").strip())
        del current_layer[num_to_menu[city_num]]
        write_data(data)
    elif choice == 'm':
        city_num=int(input("请输入要修改的城市序号!").strip())
        new_name=input("请输入新的城市名称!").strip()
        current_layer[new_name]=current_layer[num_to_menu[city_num]]
        del current_layer[num_to_menu[city_num]]
        write_data(data)
    elif choice == 'b':
        if current_layer != data:
            current_layer = last_layer[-1]
            last_layer.pop()
            continue
        else:
            print("\033[31;1myou have reach to the top layer!\033[;0m")
    elif choice == 'q':
        exit(1)
    else:
        print("\033[1;31;40m请根据提示进行选择!\033[0m")

posted on 2017-05-25 10:30  Wayne_Chen  阅读(721)  评论(0编辑  收藏  举报