基于Python的一些基础代码(系列三)

1、邮编查询 youbian.txt

 查到返回对应的城市 否则提示无此邮编

 代码:

postal_code_dict = {}

with open("D:/youbian.txt", "r", encoding="utf-8") as file:  
    for line in file.readlines():
        line = line.strip()
        if len(line) > 0:  # 确保行不为空
            try:
                # 提取邮编和城市
                parts = line[1:-1].split(',')
                postal_code = parts[0].strip()
                city = parts[1][1:-1]  # 去除双引号
                postal_code_dict[postal_code] = city
            except ValueError:
                print(f"格式错误的行: {line}")

def query_postal_code(postal_code):
    if postal_code in postal_code_dict:
        return postal_code_dict[postal_code]
    else:
        return "无此邮编"

# 测试
print(query_postal_code("110100"))

结果:

2、开房查询 kaifanglist.txt

 输入名字,查询其开房记录,如果没有,是一个单纯哥们,如果有的话,将其所有开房信息写入到以这哥们命名的文件中

代码:

def query_kaifang_record(name):
    with open("D:/kaifanglist.txt", "r", encoding="utf-8") as file:
        found = False
        records = []
        for line in file.readlines():
            parts = line.strip().split(',')
            if parts[0] == name:
                found = True
                records.append(line)
        if found:
            with open(f"{name}.txt", "w", encoding="utf-8") as output_file:
                for record in records:
                    output_file.write(record + '\n')  # 逐行写入记录
            print(f"{name} 的开房记录已写入 {name}.txt 文件")
        else:
            print(f"{name} 是个单纯哥们,没有开房记录")

# 输入名字进行查询
name = input("请输入要查询的名字:")
query_kaifang_record(name)

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值