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)
结果: