文本文件(.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 19:51:16 浏览: 58
好的,我理解了你的问题。以下是函数定义,实现你所需求的功能:
```python
def find_books_with_keyword(file_path, keyword):
books_with_keyword = []
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
fields = line.strip().split(',')
if keyword in fields[6]:
books_with_keyword.append((fields[4], fields[8]))
return books_with_keyword
def count_books_by_publisher(books):
books_by_publisher = {}
for book in books:
publisher = book[1]
if publisher in books_by_publisher:
books_by_publisher[publisher] += 1
else:
books_by_publisher[publisher] = 1
return books_by_publisher
def sort_books_by_count_desc(books_by_publisher):
return sorted(books_by_publisher.items(), key=lambda x: (-x[1], x[0]))
def write_result_to_file(file_path, books_by_publisher_sorted):
with open(file_path, 'w', encoding='utf-8') as f:
for book in books_by_publisher_sorted:
f.write(f"{book[0]},{book[1]}\n")
```
其中,`find_books_with_keyword`函数用于查找所有书名中包含“开发”字样的藏书,并返回这些藏书所属的出版社。`count_books_by_publisher`函数用于统计每个出版社的“开发”字样藏书数量。`sort_books_by_count_desc`函数用于将藏书按照数量降序排序,数量相同的按照出版社名字升序排序。`write_result_to_file`函数用于将结果写入指定的文件中。
下面是代码示例,演示如何使用这些函数:
```python
books_with_keyword = find_books_with_keyword('book.csv', '开发')
books_by_publisher = count_books_by_publisher(books_with_keyword)
books_by_publisher_sorted = sort_books_by_count_desc(books_by_publisher)
write_result_to_file('result.txt', books_by_publisher_sorted)
```
运行以上代码后,会在当前目录下生成一个名为`result.txt`的文件,其中包含了按照要求排序后的藏书信息。
阅读全文