def search(self): student_query = [] while True: id = '' name = '' if os.path.exists(self.filename): # 判断文件是否存在 mode = input('按id查找请输入1,按姓名查找请输入2\n') if mode == '1': id = input('请输入要查找的id:') elif mode == '2': name = input('请输入要查找的姓名:') else: print('您的输入有误,请重新输入') continue with open(self.filename, 'r') as rfile: allstudent = csv.DictReader(rfile) # 读取csv文件 for item in allstudent: if item['id'] == id or item['姓名'] == name: student_query.append(item) # 查询是否有对应id或姓名的学生,找到之后放到查询结果列表中 # 显示查询结果 self.show_student(student_query) answer = input('是否要继续查询?y/n\n') if answer == 'y' or answer == 'Y': # 清空列表 student_query.clear() continue else: break else: print('暂未保存该学生信息') return # 展示所有学生 def show(self): if os.path.exists(self.filename): with open(self.filename, 'r') as rfile: reader = csv.reader(rfile) # 读取csv文件 student_information = [] # 将结果转换为列表 for row in reader: student_information.append(row) if student_information != []: self.formet.output(student_information) # 调用格式化的展示函数 else: print('暂未保存学生信息')请你帮我修正错误

时间: 2024-03-02 10:49:21 浏览: 21
这段代码中似乎没有明显的错误,但是可以做一些改进和优化: 1. 在查询学生信息时,可以使用 `input` 函数的参数来限制用户输入的值,而不是用 `continue` 语句来强制用户重新输入。例如: ``` mode = input('按id查找请输入1,按姓名查找请输入2\n[1/2]: ') while mode not in ['1', '2']: print('您的输入有误,请重新输入') mode = input('按id查找请输入1,按姓名查找请输入2\n[1/2]: ') ``` 2. 在读取 CSV 文件时,可以使用 `csv.DictReader` 函数来读取,这样可以直接将每行数据转换为字典格式,方便查询和处理。 3. 在展示学生信息时,可以使用 `csv.reader` 函数的 `DictReader` 类来读取,这样可以直接将每行数据转换为字典格式,方便展示和处理。 4. 可以添加一些异常处理机制,例如文件不存在或者读取错误时,给出提示和处理方法。 下面是修改后的代码: ``` import csv import os class Student: def __init__(self, filename, formet): self.filename = filename self.formet = formet def search(self): student_query = [] while True: id = '' name = '' if not os.path.exists(self.filename): print('暂未保存该学生信息') return mode = input('按id查找请输入1,按姓名查找请输入2\n[1/2]: ') while mode not in ['1', '2']: print('您的输入有误,请重新输入') mode = input('按id查找请输入1,按姓名查找请输入2\n[1/2]: ') if mode == '1': id = input('请输入要查找的id:') elif mode == '2': name = input('请输入要查找的姓名:') with open(self.filename, 'r') as rfile: allstudent = csv.DictReader(rfile) for item in allstudent: if item['id'] == id or item['姓名'] == name: student_query.append(item) if student_query: self.show_student(student_query) else: print('未找到符合条件的学生信息') answer = input('是否要继续查询?[y/n]: ') if answer.lower() != 'y': break student_query.clear() def show(self): if not os.path.exists(self.filename): print('暂未保存学生信息') return with open(self.filename, 'r') as rfile: reader = csv.DictReader(rfile) student_information = [] for row in reader: student_information.append(row) if student_information: self.formet.output(student_information) else: print('暂未保存学生信息') def show_student(self, students): headers = ['id', '姓名', '性别', '年龄', '成绩'] student_information = [headers] for student in students: row = [student[h] for h in headers] student_information.append(row) self.formet.output(student_information) class Formet: def output(self, student_information): for row in student_information: print('\t'.join(row)) filename = 'students.csv' student = Student(filename, Formet()) student.search() ```

相关推荐

将下面代码简洁化:def split_dataset(img_path, target_folder_path, output_path): filename = [] total_imgs = os.listdir(img_path) #for root, dirs, files in os.walk(img_path): for img in total_imgs: filename.append(img) np.random.shuffle(filename) train = filename[:int(len(filename) * 0.9)] test = filename[int(len(filename) * 0.9):] out_images = os.path.join(output_path, 'imgs') if not os.path.exists(out_images): os.makedirs(out_images) out_images_train = os.path.join(out_images, 'training') if not os.path.exists(out_images_train): os.makedirs(out_images_train) out_images_test = os.path.join(out_images, 'test') if not os.path.exists(out_images_test): os.makedirs(out_images_test) out_annotations = os.path.join(output_path, 'annotations') if not os.path.exists(out_annotations): os.makedirs(out_annotations) out_annotations_train = os.path.join(out_annotations, 'training') if not os.path.exists(out_annotations_train): os.makedirs(out_annotations_train) out_annotations_test = os.path.join(out_annotations, 'test') if not os.path.exists(out_annotations_test): os.makedirs(out_annotations_test) for i in train: print(os.path.join(img_path, i)) print(os.path.join(out_images_train, i)) shutil.copyfile(os.path.join(img_path, i), os.path.join(out_images_train, i)) annotations_name = "gt_" + i[:-3] + 'txt' shutil.copyfile(os.path.join(target_folder_path, annotations_name), os.path.join(out_annotations_train, annotations_name)) for i in test: shutil.copyfile(os.path.join(img_path, i), os.path.join(out_images_test, i)) annotations_name = "gt_" + i[:-3] + 'txt' shutil.copyfile(os.path.join(target_folder_path, annotations_name), os.path.join(out_annotations_test, annotations_name))

帮我把一下代码设置一个合理请求头,并加入一个延时import requests import os from bs4 import BeautifulSoup class NovelDownloader: def __init__(self, root_url): self.root_url = root_url self.book_list = [] self.chapter_list = [] def get_url(self, url): while True: try: res = requests.get(url) if res.status_code == 200: print("页面获取成功!") return res.text else: print("页面返回异常!", res.status_code) except: print("页面获取错误!") def get_book_list(self): res = self.get_url(self.root_url) html = BeautifulSoup(res, "html.parser") a_list = html.find_all("a", {"class": "name"}) for a in a_list: self.book_list.append(a["href"]) self.book_list = [self.root_url + i for i in self.book_list] self.book_list.remove('http://www.biquge5200.cc/') def get_chapter_list(self, url): res = self.get_url(url) html = BeautifulSoup(res, "html.parser") a_list = html.find_all("a", {"class": "chapter"}) for a in a_list: self.chapter_list.append((a["href"], a.text.replace("\n", ""))) def get_content(self, chapter): url = self.root_url + chapter[0] print(url) book_name = chapter[0].split("/")[1] print(book_name) if not os.path.exists(book_name): os.mkdir(book_name) res = self.get_url(url) html = BeautifulSoup(res, "html.parser") content = html.find("div", {"id": "content"}).text print(content) path = os.path.join(book_name, chapter[1]) with open(path, "w", encoding="utf8") as f: f.write(content) def main(self): self.get_book_list() for book in self.book_list: self.get_chapter_list(book) for chapter in self.chapter_list: self.get_content(chapter) if __name__ == '__main__': root_url = "http://www.biquge5200.cc/" nd = NovelDownloader(root_url) nd.main()

优化代码 def fault_classification_wrapper(vin, main_path, data_path, log_path, done_path): start_time = time.time() isc_path = os.path.join(done_path, vin, 'isc_cal_result', f'{vin}_report.xlsx') if not os.path.exists(isc_path): print('No isc detection input!') else: isc_input = isc_produce_alarm(isc_path, vin) ica_path = os.path.join(done_path, vin, 'ica_cal_result', f'ica_detection_alarm_{vin}.csv') if not os.path.exists(ica_path): print('No ica detection input!') else: ica_input = ica_produce_alarm(ica_path) soh_path = os.path.join(done_path, vin, 'SOH_cal_result', f'{vin}_sohAno.csv') if not os.path.exists(soh_path): print('No soh detection input!') else: soh_input = soh_produce_alarm(soh_path, vin) alarm_df = pd.concat([isc_input, ica_input, soh_input]) alarm_df.reset_index(drop=True, inplace=True) alarm_df['alarm_cell'] = alarm_df['alarm_cell'].apply(lambda _: str(_)) print(vin) module = AutoAnalysisMain(alarm_df, main_path, data_path, done_path) module.analysis_process() flags = os.O_WRONLY | os.O_CREAT modes = stat.S_IWUSR | stat.S_IRUSR with os.fdopen(os.open(os.path.join(log_path, 'log.txt'), flags, modes), 'w') as txt_file: for k, v in module.output.items(): txt_file.write(k + ':' + str(v)) txt_file.write('\n') for x, y in module.output_sub.items(): txt_file.write(x + ':' + str(y)) txt_file.write('\n\n') fc_result_path = os.path.join(done_path, vin, 'fc_result') if not os.path.exists(fc_result_path): os.makedirs(fc_result_path) pd.DataFrame(module.output).to_csv( os.path.join(fc_result_path, 'main_structure.csv')) df2 = pd.DataFrame() for subs in module.output_sub.keys(): sub_s = pd.Series(module.output_sub[subs]) df2 = df2.append(sub_s, ignore_index=True) df2.to_csv(os.path.join(fc_result_path, 'sub_structure.csv')) end_time = time.time() print("time cost of fault classification:", float(end_time - start_time) * 1000.0, "ms") return

最新推荐

recommend-type

node-v4.9.0-linux-armv7l.tar.xz

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
recommend-type

node-v4.8.4-linux-armv6l.tar.xz

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

list根据id查询pid 然后依次获取到所有的子节点数据

可以使用递归的方式来实现根据id查询pid并获取所有子节点数据。具体实现可以参考以下代码: ``` def get_children_nodes(nodes, parent_id): children = [] for node in nodes: if node['pid'] == parent_id: node['children'] = get_children_nodes(nodes, node['id']) children.append(node) return children # 测试数
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这
recommend-type

未定义标识符CFileFind

CFileFind 是MFC(Microsoft Foundation Class)中的一个类,用于在Windows文件系统中搜索文件和目录。如果你在使用CFileFind时出现了“未定义标识符”的错误,可能是因为你没有包含MFC头文件或者没有链接MFC库。你可以检查一下你的代码中是否包含了以下头文件: ```cpp #include <afx.h> ``` 另外,如果你在使用Visual Studio开发,还需要在项目属性中将“使用MFC”设置为“使用MFC的共享DLL”。这样才能正确链接MFC库。