Python基础之I/O操作-2
题1文件读取、字符串拆分任务编写函数count_words_in_file(filename)读取指定文本文件返回文件中的总单词数单词以空格等分隔。示例假设test.txt内容如下则函数返回4。Hello world Hello Python# 方案一: 一次性读取完整个文件内容适用于文件比较小的情况defcount_words_in_file(filename):fropen(filename,rt,encodingutf-8)datafr.read()fr.close()returnlen(data.split())print(单词数量:,count_words_in_file(test.txt))# 方案二:按行统计defcount_words_in_file(filename):fropen(filename,rt,encodingutf-8)count0forlineinfr:countlen(line.split())fr.close()returncountprint(单词数量:,count_words_in_file(test.txt))题2文件写入、字典操作任务编写函数save_contacts(contacts, filename)将通讯录字典键为姓名值为电话保存到文件中每行格式为姓名:电话。再编写load_contacts(filename)从文件中读取并重建字典。contacts{张三:10086,李四:10011,王五:123456}# 读取defsave_contacts(contacts,filename):fropen(filename,at,encodingutf-8)forname,telincontacts.items():fr.write(name:tel\n)fr.close()save_contacts(contacts,tel.txt)# 写入defload_contacts(filename):contacts{}fropen(filename,rt,encodingutf-8)forlineinfr:name,telline.strip().split(:)contacts[name]tel fr.close()returncontactsprint(load_contacts(tel.txt))题3文件逐行读取、字符串处理任务有一个日志文件log.txt每行格式为时间 - 级别 - 消息例如2023-01-01 10:00 - ERROR - Disk full。编写函数count_log_levels(filename)统计并返回一个字典记录每个日志级别INFO、WARNING、ERROR出现的次数。示例{ERROR: 5, WARNING: 3, INFO: 10}2023-01-01 10:00 - ERROR - Disk full 2023-01-01 10:05 - INFO - Systemstarted 2023-01-01 10:10 - WARNING - Low memory 2023-01-01 10:15 -INFO - User logged in 2023-01-01 10:20 - ERROR - Connection timeoutlog.txt文件内容defcount_log_levels(filename):dict_demo{}fropen(filename,rt,encodingutf-8)forlineinfr:_,level,_line.split( - )dict_demo[level]dict_demo.get(level,0)1fr.close()returndict_demoprint(count_log_levels(log.txt))