文本文件(.csv文件可以作为文本文件处理)中保存了图书馆藏书信息,每条藏书记录占一行 数据字段说明: LIBRARY_ID:藏馆ID(可能有多个藏馆) REC_CTRL_I:录入编号 BOOK_BARCO:图书条码 DEPARTMENT:所属部门 BOOK_SEARC:索书号 TITLE:图书名称 ISN:ISBN出版号 AUTHORS:作者 PUBLISHER:出版社 PUBDATE_DA:出版时间 BOOK_ATTRI:图书属性 BOOK_STATU:图书状态 (用函数定义,不用pandas)列出所有书名中包括“开发”字样的藏书和这些藏书所属的出版社,函数定义(不用pandas)统计每个出版社的”开发“字样藏书数量,用函数定义(不用pandas)按照该藏书数量降序输出,数量相同按照出版社名字升序。用函数定义(不用pandas)将结果写入result.txt文件中
时间: 2024-03-04 15:51:18 浏览: 24
好的,下面是代码实现:
```python
def find_books_with_keyword(file_path, keyword):
book_list = []
with open(file_path, 'r') as f:
for line in f:
if keyword in line:
book_info = line.strip().split(',')
book_name = book_info[6]
publisher = book_info[9]
book_list.append((book_name, publisher))
return book_list
def count_books_by_publisher(book_list):
publisher_dict = {}
for book in book_list:
publisher = book[1]
if publisher not in publisher_dict:
publisher_dict[publisher] = 1
else:
publisher_dict[publisher] += 1
return publisher_dict
def sort_publishers_by_book_count(publisher_dict):
sorted_publishers = sorted(publisher_dict.items(), key=lambda x: (-x[1], x[0]))
return sorted_publishers
def write_result_to_file(file_path, sorted_publishers):
with open(file_path, 'w') as f:
for publisher in sorted_publishers:
f.write(publisher[0] + ',' + str(publisher[1]) + '\n')
if __name__ == '__main__':
file_path = 'book_info.csv'
keyword = '开发'
book_list = find_books_with_keyword(file_path, keyword)
publisher_dict = count_books_by_publisher(book_list)
sorted_publishers = sort_publishers_by_book_count(publisher_dict)
write_result_to_file('result.txt', sorted_publishers)
```
代码中,`find_books_with_keyword`函数用于查找包含关键字的书籍信息,返回一个列表,列表中每个元素是一个元组,元组中第一个元素是书名,第二个元素是出版社。
`count_books_by_publisher`函数用于统计每个出版社包含关键字的书籍数量,返回一个字典,键是出版社名,值是包含关键字的书籍数量。
`sort_publishers_by_book_count`函数用于将出版社进行排序,先按照包含关键字的书籍数量降序排序,再按照出版社名字升序排序。
`write_result_to_file`函数用于将排序后的结果写入文件。
在程序中,我们可以通过修改`file_path`和`keyword`参数来处理不同的CSV文件和不同的关键字。执行程序后,将会在当前目录下生成`result.txt`文件,文件中包含按照要求排序后的结果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)