美文网首页Python学习手册
Python实现-省市县三级菜单(3种方法)

Python实现-省市县三级菜单(3种方法)

作者: 复苏的兵马俑 | 来源:发表于2020-03-09 21:52 被阅读0次
    1、要求

      1)下载中国省市县的json文件(文件命名为china_Citys.json);
      2)一级、二级、三级菜单分别对应省/直辖市/自治区/特别行政区、市/地区、县/区;
      3)一级、二级菜单有输入对应代码进入下一级的功能;
      4)实现返回上一级和退出机制的功能。

    2、分析
    2.1 获取数据源

      1)中国省市县json文件下载链接,可关注微信公众号“全栈POT修炼”,并回复“8001”获取;
      2)最新的区划和城乡划分代码数据,可通过国家统计局-统计用区划和城乡划分代码抓取,并制作成json文件“china_Citys.json”。

    2.2 分析步骤

      1)进入程序,显示省/直辖市/自治区/特别行政区的名字(也可带上对应的数字编号),以多列的形式来显示;
      2)提示输入省/直辖市/自治区/特别行政区的名字(或编号),输入正确则进入并打印对应的市/地区的列表,非法输入则提示重新输入,提示输入“q”或“Q”来退出程序;
      3)从市/地区进入县/区同2),并提示输入“r”或“R”返回上一级;
      4)县/区界面,提示输入“q”或“Q”来退出程序,提示输入“r”或“R”返回上一级;
      5)使用while来循环。

    3、代码

    方案一(通过条件控制实现):

    # 导入json文件
    import json
    filename = 'china_Citys.json'
    with open(filename, encoding= 'utf-8') as f:
        china_Citys = json.load(f)
    
    # 全局参数
    columns = 4
    
    # 打印省级/直辖市/自治区/特别行政区的函数
    def print_Province():
        count = 0
        for i in range(len(china_Citys)):
            count += 1
            print('%02d'.ljust(5, ':') %i,china_Citys[i]['label'].ljust(15, ' '), end = '')
            # 用于打印成三列
            if count % columns == 0:
                print('')
        print('\n')
    
    # 打印市级/地区的函数
    def print_City(province_Number):
        count = 0
        for i in range(len(china_Citys[province_Number]['children'])):
            count += 1
            print('%02d'.ljust(5, ':') %i,china_Citys[province_Number]['children'][i]['label'].ljust(20, ' '), end = '')
            # 用于打印成三列
            if count % columns == 0:
                print('')
        print('\n')
    
    # 打印县级/区级的函数
    def print_County(province_Number,City_Number):
        count = 0
        for i in range(len(china_Citys[province_Number]['children'][city_Number]['children'])):
            count += 1
            print('%02d'.ljust(5, ':') %i,china_Citys[province_Number]['children'][city_Number]['children'][i]['label'].ljust(20, ' '), end = '')
            # 用于打印成三列
            if count % columns == 0:
                print('')
        print('\n')
    
    # 定位标志
    location_Mark = 0
    
    while 1:
    
        # 打印省级/直辖市/自治区/特别行政区
        if location_Mark == 0:
            print_Province()
            location_Mark = 1
    
        if location_Mark == 1:
            # 提示输入省级/直辖市/自治区/特别行政区编号进入市级/地区,并提示输入‘q’或‘Q’退出
            province_Number = input('请输入省级/直辖市/自治区/特别行政区的编号以进入市级/地区,输入‘q’或‘Q’退出,输入‘p’或‘P’打印省级/直辖市/自治区/特别行政区:').strip()
            if province_Number.upper() == 'Q':
                print('结束输入!')
                break
            elif province_Number.upper() == 'P':
                print_Province()
            elif province_Number.isdigit() and int(province_Number) >= 0 and int(province_Number) <= len(china_Citys):
                province_Number = int(province_Number)
                print_City(province_Number)
                location_Mark = 2
            else:
                print('你输入的不正确,请重新输入!')
    
        if location_Mark == 2:
            # 提示输入市级/地区编号进入县级/区级,并提示输入‘q’或‘Q’退出,输入‘r’或‘R’返回上一级
            city_Number = input('请输入市级/地区的编号以进入县级/区级,输入‘q’或‘Q’退出,输入‘b’或‘B’返回上一级,输入‘c’或‘C’打印市级/地区:').strip()
            if city_Number.upper() == 'Q':
                print('结束输入!')
                break
            elif city_Number.upper() == 'B':
                location_Mark = 1
            elif city_Number.upper() == 'C':
                print_City(province_Number)
            elif city_Number.isdigit() and int(city_Number) >= 0 and int(city_Number) <= len(china_Citys[province_Number]['children']):
                city_Number = int(city_Number)
                print_County(province_Number,city_Number)
                location_Mark = 3
            else:
                print('你输入的不正确,请重新输入!')
    
        if location_Mark == 3:
            # 提示输入‘q’或‘Q’退出,输入‘r’或‘R’返回上一级
            exit_or_Return = input('请输入‘q’或‘Q’退出,输入‘b’或‘B’返回上一级:').strip()
            if exit_or_Return.upper() == 'Q':
                print('结束输入!')
                break
            elif exit_or_Return.upper() == 'B':
                location_Mark = 2
            else:
                print('请输入‘q’或‘Q’退出,‘b’或‘B’返回!')
    

    方案二(通过迭代实现):

    # 导入json文件
    import json
    filename = 'china_Citys.json'
    with open(filename, encoding= 'utf-8') as f:
        china_Citys = json.load(f)
    
    # 重组json成层叠字典
    china_Citys_Dic = {}
    for province_Total in china_Citys:
        city_Temp = {}
        for city_Total in province_Total['children']:
            country_Temp = {}
            for country_Total in city_Total['children']:
                country_Temp[country_Total['label']] = {}
            city_Temp[city_Total['label']] = country_Temp
        china_Citys_Dic[province_Total['label']] = city_Temp
    
    def three_Menu(citys_Dic):
        columns = 4
        while 1:
            count = 0
            for k in citys_Dic:
                count += 1
                print(k.ljust(15, ' '), end='')
                if count % columns == 0:
                    print('')
            choice = input('\n请输入需要查询的名称,输入‘q’或‘Q’退出,输入‘b’或‘B’返回上一级:').strip()
            if choice.upper() == 'B' or choice.upper() == 'Q':
                return choice
            elif choice in citys_Dic.keys() and citys_Dic[choice]:
                result = three_Menu(citys_Dic[choice])
                if result.upper() == 'Q':
                    return 'Q'
            elif choice in citys_Dic.keys() and not citys_Dic[choice]:
                print('已经是最底层了!')
            else:
                print('你的输入不正确,请重新输入!')
    
    three_Menu(china_Citys_Dic)
    

    方案三(通过堆栈实现):

    # 导入json文件
    import json
    filename = 'china_Citys.json'
    with open(filename, encoding= 'utf-8') as f:
        china_Citys = json.load(f)
    
    # 重组json成层叠字典
    china_Citys_Dic = {}
    for province_Total in china_Citys:
        city_Temp = {}
        for city_Total in province_Total['children']:
            country_Temp = {}
            for country_Total in city_Total['children']:
                country_Temp[country_Total['label']] = {}
            city_Temp[city_Total['label']] = country_Temp
        china_Citys_Dic[province_Total['label']] = city_Temp
    
    # 全局参数
    columns = 4
    exit_Active = False
    current_Class = china_Citys_Dic
    parent_Class = [china_Citys_Dic]
    
    while not exit_Active:
        flag = 1
        count = 0
        for k in current_Class:
            count += 1
            print(k.ljust(15, ' '), end = '')
            if count % columns == 0:
                print('')
        choice = input('\n请输入需要查询的名称,输入‘q’或‘Q’退出,输入‘b’或‘B’返回上一级:').strip()
        if choice.upper() == 'B' and parent_Class != []:
            current_Class = parent_Class[-1]
            parent_Class.pop()
        elif choice.upper() == 'Q':
            exit_Active = True
            print('结束输入!')
        elif choice not in current_Class:
            print('你输入的不正确,请重新输入!')
            continue
        elif not current_Class[choice]:
            print('已经是最底层了!')
            continue
        else:
            if current_Class not in parent_Class:
                parent_Class.append(current_Class)
            current_Class = current_Class[choice]
    
    附录:

      省市县json文件命名为“china_Citys.json”,文件下载链接请关注微信公众号“全栈POT修炼”,并回复“8001”获取。


    “全栈POT修炼”

    相关文章

      网友评论

        本文标题:Python实现-省市县三级菜单(3种方法)

        本文链接:https://www.haomeiwen.com/subject/hirpdhtx.html