风-fmgao

导航

省市县_me

# question   11
import ast
from functools import reduce


def file_read():
    with open('D:\\pytharm\\jichuyufa\\day2\\pro_cty_con.txt', 'r', encoding='utf8') as f:
        san_dic = ast.literal_eval(f.read())
        return san_dic


dic = file_read()
print(dic)
ke = list(dic.keys())
print('provinces:', ke)
# print('-----------------')
cits = []
township = []
for i in ke:
    # print(dic[i])
    for j in dic[i]:
        # print(j)
        cits.append(j)
        township.append(dic[i][j])
        # print(dic[i][j])
print('citys:', cits)
# print('-----------------')
# print('township:', township)
township = reduce(lambda x, y: x + y, township)
print('township:', township)


def file_wi(dic_add):
    with open('D:\\pytharm\\jichuyufa\\day2\\pro_cty_con.txt', 'w+', encoding='utf8') as f:
        f.write(dic_add)
        # pass


def add_dic(dic):
    dic_insert = {}
    dic_insert1 = {}
    li_insert = []
    new_flag = True
    while new_flag:
        pro_new = input('输入Q结束:输入q返回,输入要添加的省')
        if pro_new == 'q':
            break
        elif pro_new == 'Q':
            exit()
        elif pro_new in ke:
            print('省份已经存在')
            cit_bool = input('输入y或者Y,要在该省添加城市')
            if cit_bool.lower() == 'y':
                # pass
                cty_new = input('输入Q结束:输入q返回,输入要添加的市')
                if cty_new == 'q':
                    break
                elif cty_new == 'Q':
                    exit()
                elif cty_new in cits:
                    print('该城市已经存在')
                    town_bool = input('输入y或者Y,要在该城市添加县')
                    if town_bool.lower() == 'y':
                        while True:
                            township_new = input('输入Q结束:输入q返回,输入要添加的县')
                            if township_new == 'q':
                                break
                            elif township_new == 'Q':
                                exit()
                            elif township_new in township:
                                print('该县已经存在')
                            else:
                                print(1)
                                # 新数据构造字典
                                dic[pro_new][cty_new].append(township_new)
                        new_flag = False
                    else:
                        continue
                else:
                    while True:
                        township_new = input('输入Q结束:输入q返回,输入要添加的县')
                        if township_new == 'q':
                            break
                        elif township_new == 'Q':
                            exit()
                        elif township_new in township:
                            print('该县已经存在')
                        else:
                            print(1)
                            # 新数据构造字典
                            li_insert.append(township_new)
                            dic_insert1[cty_new] = li_insert
                            dic_city_is = dic[pro_new]
                            # print(dic_city_is, type(dic_city_is))
                            dic_city_is = dict(dic_city_is, **dic_insert1)
                            dic_insert[pro_new] = dic_city_is
                    new_flag = False
            else:
                continue
        else:
            cty_new = input('输入Q结束:输入q返回,输入要添加的市')
            if cty_new == 'q':
                break
            elif cty_new == 'Q':
                exit()
            elif cty_new in cits:
                print('该城市已经存在')
                continue
            else:
                while True:
                    township_new = input('输入Q结束:输入q返回,输入要添加的县')
                    if township_new == 'q':
                        break
                    elif township_new == 'Q':
                        exit()
                    elif township_new in township:
                        print('该县已经存在')
                    else:
                        print(1)
                        # 新数据构造字典
                        li_insert.append(township_new)
                        dic_insert1[cty_new] = li_insert
                        dic_insert[pro_new] = dic_insert1
                new_flag = False
    print(dic_insert)
    # 字典合并
    dic = dict(dic, **dic_insert)
    print(dic)
    file_wi(str(dic))


# 调用添加方法
# add_dic(dic)


def dic_display(dic):
    # 定义颜色
    def get_color(text, color='red'):
        """
        将字符串格式化为带颜色内容
        :param text: 接收字符串
        :param color:默认红色
        :return: ->str 返回带颜色的内容
        """
        color_table = {
            "red": "\033[31m",
            "green": "\033[32;1m",
            "yellow": "\033[33;1m",
            "purple": "\033[36;1m",
            "end": "\033[0m",  # 结束符号
        }
        li = [color_table.get(color), str(text), color_table["end"]]
        print(li)
        return ''.join(li)
    while True:
        province = input('输入Q结束,输入你喜欢的省:')
        if len(province) == 0:
            print("不能为空!")
            continue
        elif province == 'Q':
            exit()
        elif province not in dic:
            print('天朝的省份都不知道,打死你哥龟孙!!!')
            continue
        city_list=[]
        for i in dic[province]:
            city_list.append(i)
        # print(city_list)
        print(get_color('%s省包括:%s' % (province, city_list), 'green'))

        while True:
            city = input("输入Q结束:输入q返回,输入城市查看县:")
            if city == 'q':
                break
            elif city == 'Q':
                exit()
            elif city in city_list:             #必须放倒最后否则下面的while不会被执行
                township = dic[province][city]
                print(get_color('%s县包括:%s' % (city,township),'yellow'))

                while True:
                    county = input("输入Q结束,输入q返回,输入县进入县:")
                    if county == 'q':
                            break
                    elif county == 'Q':
                        exit()
                    elif county in township:
                        print(get_color(('%s县欢迎您!!!' % county),'purple'))

# 调用显示方法
# dic_display(dic)


while True:
    cho_ic = input('退出输入T,显示输入1,添加输入2')
    print(cho_ic)
    if cho_ic == '1':
        # print(11111111111111)
        dic_display(dic)
    elif cho_ic == '2':
        # print(2222222222222)
        add_dic(dic)
    elif cho_ic == 'T':
        break
    else:
        print('请按照要求输入')

 

数据

{'江西': {'萍乡': ['安源', '彭高', '上栗'], '新余': ['良山', '新钢', '兴安岭']}, '北京': {'大兴区': ['礼贤镇', '魏善庄镇', '北臧村镇'], '昌平区': ['沙河', '化庄', '白浮泉']}, '福建': {'莆田': ['荔城', '西天尾', '九化山'], '厦门': ['湖里', '思明', '海仓']}, '山西': {'大同': ['左权', '左权1', '左权2'], '太原': ['小店', '清徐', '榆次', '太1', '太23']}, '辽宁': {'沈阳': ['东一', '东二', '东单']}}

 

posted on 2018-05-16 17:22  风-fmgao  阅读(82)  评论(0编辑  收藏  举报