import os import re def sort_chapters(files): """根據檔名中提取的章節編號對檔案進行排序。""" # 此正規表示式假設章節編號是數字,並嘗試提取以進行排序 chapter_pattern = re.compile(r'\d+') def extract_number(file): match = chapter_pattern.search(file) if match: return int(match.group()) return 0 # 如果未找到數字,則預設為0 return sorted(files, key=extract_number) def find_novel(book_name): # 構建儲存所有小說的基礎目錄路徑 base_directory = "..\\小說" # 列出基礎目錄中的所有目錄 all_directories = os.listdir(base_directory) # 搜尋與書名匹配的目錄 matching_directories = [directory for directory in all_directories if book_name in directory] if not matching_directories: print("未找到給定書名的目錄。") return book = {} # 建立一個空字典用於儲存章節名和內容 # 遍歷匹配的目錄 for directory in matching_directories: novel_path = os.path.join(base_directory, directory) print(f"目錄:{novel_path}") # 列出目錄中的所有檔案並對其進行排序 files = os.listdir(novel_path) sorted_files = sort_chapters(files) # 遍歷排序後的txt檔案並將其內容儲存在字典中 for file in sorted_files: if file.endswith('.txt'): with open(os.path.join(novel_path, file), 'r', encoding='utf-8') as f: content = f.read() # 提取章節名,假設檔名就是章節名 chapter_name = os.path.splitext(file)[0] book[chapter_name] = content return book