中原省市区菜单

1、演习供给

  • 从网络找到中华夏族民共和国省市区的json或字典数据
  • 1、2、三级菜单分别对应省市区,且各种都有单独的代码
  • 省、市菜单有输入相应代码进入下一级功能
  • 有重回上一流效用和退出机制

2、演练分析

2.一 获取源数据

  1. 全国省市区json——来源于csdb,复制数据并另存为json格式。(最棒在复制后去在线json检查测试网址检查是或不是valid)

  2. 最林州市及县以上行政区划代码——来源于总结局,复制成文本格式,中期再通过python来解析txt获取并整合{(代码,省):{(代码,市):{(代码,区)}}}

  3. 直接通过总计局的网址,通过抓取来生成json文件(那几个麻烦一些)

二.2 步骤分析

  1. 用函数来贯彻模块很有益于,新手演习依旧逐层达成
  2. 跻身程序,突显省的名字和呼应数字列表,以叁列的花样来展现
  3. lehuguoji乐虎国际网址,唤醒输入省级代码,输入正确则进入对应市级列表;输入违规则提示重新输入;指示输入‘q’来退出程序(用break循环)
  4. 市级进到县级同上;其它,提醒输入‘r’来回到上拔尖
  5. 县级分界面,提醒输入‘r’来回到上超级,‘q’来退出程序
  6. 进行标记位,全部用while来循环

三、代码达成

  • 以json方法来促成最为迅猛
  • json文件命名叫“City_json.json ”
  • #### 上面是本子1:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'''China province to city, to district'''
__author__:'Wu HH'

# 导入json文件
import json
filename = 'City_json.json'
with open(filename, 'r') as file:
    china_data = json.load(file)

# 打印省级的函数
def print_pro():
    count = 0
    for i in range(len(china_data)):
        count += 1
        print(china_data[i]['name'].ljust(8,'>'),'%02d'.ljust(6,' ') % i, end='')
        # 用于打印成3列
        if count % 3 == 0:
            print('')

# 打印市级的函数
def print_city(city_num):
    count = 0
    for i in range(len(china_data[city_num]['city'])):
        count += 1
        print(china_data[city_num]['city'][i]['name'].ljust(8,'>'),'%02d'.ljust(6,' ') % i, end='')
        # 用于打印成3列
        if count % 3 == 0:
            print('')

# 打印县级的函数
def print_area(city_num, area_num):
    count = 0
    for i in range(len(china_data[city_num]['city'][area_num]['area'])):
        count += 1
        print(china_data[city_num]['city'][area_num]['area'][i].ljust(8,'>'),'%02d'.ljust(6,' ') % i, end='')
        # 用于打印成3列
        if count % 3 == 0:
            print('')

# 定位标志
loca_num = 0

while True:

    # 打印省级
    if loca_num == 0:
        print_pro()
        loca_num = 1

    if loca_num == 1:
        # 提示输入省级编号进入市级,并提示q退出
        into_city_num = input('Please input number to get into city. "q" to quit. ')
        if into_city_num == 'q':
            break
        elif int(into_city_num) > 0 and int(into_city_num) <= len(china_data):
            into_city_num = int(into_city_num)
            if loca_num == 1:
                print_city(into_city_num)
            loca_num = 2
        else:
            print('please input a valid number')

    if loca_num == 2:
        # 提示输入市级编号进入县级,并提示q退出,r返回上一级
        into_area_num = input('Please input number to get into city. "q" to quit. "r" to return. ')
        if into_area_num == 'q':
            break
        elif into_area_num == 'r':
            loca_num = 0
            continue
        elif int(into_area_num) > 0 and int(into_area_num) <= len(china_data[into_city_num]['city']):
            into_area_num = int(into_area_num)
            if loca_num == 2:
                print_area(into_city_num, into_area_num)
            loca_num = 3
        else:
            print('please input a valid number')

    if loca_num == 3:
        # 提示q退出,r返回上一级
        input_in_area = input('"q" to quit. "r" to return. ')
        if input_in_area == 'q':
            break
        elif input_in_area == 'r':
            loca_num = 2
            print_city(into_city_num)
            continue
        else:
            print("please input a 'q' or 'r'")
  • ### 下边是优化版本二:(网络找的天涯论坛-金角大王)

  • 很钦佩这些版本,可是互相是经过输入完毕城市名而不是数字

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'''more elegent version of China province program'''
__author__:'Wu HH'

# 导入json文件
import json
filename = 'City_json.json'
with open(filename, 'r') as file:
    china_data = json.load(file)

# 重组json成层叠字典{a:{b1:{c1:[]},c2:{}},b2:{...}...}
china_data_dic = {}
for province_total in china_data:
    city_temp = {}
    for city_total in province_total['city']:
        city_temp[city_total['name']] = city_total['area']
    china_data_dic[province_total['name']] = city_temp


exit_active = False

current_class = china_data_dic
parent_classes = [china_data_dic]

while not exit_active:
    count_num = 0
    for k in current_class:
        count_num += 1
        print(k.ljust(8, ' '),end='')
        if count_num % 3 == 0:
            print('')
    choice = input(">>:").strip()
    if choice == 'b' and parent_classes != []:
        current_class = parent_classes[-1]
        parent_classes.pop()
    elif choice == 'q':
        exit_active = True
    elif choice not in current_class:
        continue
    else:
        if current_class not in parent_classes:
            parent_classes.append(current_class)
        try:
            current_class = current_class[choice]
        except TypeError:
            continue

寻思了好一阵子都没悟出怎么化解“县级在非合法输入后,须要‘b’三遍才干回去市级”的bug。先留着,现在有空继续考虑

You can leave a response, or trackback from your own site.

Leave a Reply

网站地图xml地图