kaifanglist.txt中记录用户住宿记录,包括:姓名,身份证号,性别,生日,家庭住址,邮编,手机号,座机号,单位电话,qq号,其他信息,记录中有些信息没有值,一行就是一个住宿记录。请你根据文件内容完成以下功能:
(1)读入文件内容,对数据清洗,把没有值的记录补齐,例如生日没有值,则填入’无’;值是’-‘替换为’无’;其他信息没有的则填入0
(2)一行生成一个对象,对象所属的类自己定义
(3)根据用户输入的用户名或身份证号,查询住宿记录,包括所有的记录
(4)可以连续查询
(5)结束程序时,建立一个线程,把修改后的数据写入源文件
代码如下:
import csv
class Person:
def init(self,**info):
# 属性赋值
self.dict.update(info)
# 重写的关系运算符 <
def __lt__(self, other):
return self.no < other.no
def __str__(self):
res= ''
for key in self.__dict__:
res += self.__dict__[key] + '\t'
return res
class QueryManagement:
def init(self,fileName):
self.fileName = fileName
self.personList = []
self.load_file() # 加载查询文件
# 加载文件
def load_file(self):
with open(self.fileName,encoding='utf8') as fp:
reader = csv.reader(fp)
next(reader) # 跳过标题
for line in reader:
# 补齐11个属性
line = line + ['无']*(11-len(line))
line = ['无' if value=='' or value=='-' else value for value in line]
line[-1] = '0'
self.personList.append(self.generate_object(line))
def generate_object(self,values):
keys = ['name','ID','sex','birthday','address','zipcode','phone','telephone','workcell','qq','other']
info = dict(zip(keys,values))
return Person(**info)
def display(self):
for person in self.personList:
print(person)
def find_by_name(self,name):
res = []
for person in self.personList:
if person.name.lower() == name.lower():
res.append(person)
return res
def find_by_ID(self,ID):
res = []
for person in self.personList:
if person.ID == ID:
res.append(person)
return res
# 查询
def query(self):
while 1:
print("1.按姓名查询")
print("2.按身份证号查询")
print("0.退出")
choice = int(input("请输入你的选择:"))
if choice == 0:
break
elif choice == 1:
name = input("请输入查找的姓名:")
res = self.find_by_name(name)
for person in res:
print(person)
elif choice == 2:
ID = input("请输入身份证号:")
res= self.find_by_ID(ID)
for person in res:
print(person)
else:
print("没有该选项,请重新选择")
if name == ‘main’:
res = QueryManagement(“kaifanglist.txt”)
res.query()