Python 文本阅读器:跳转指定章节
Python 文本阅读器:跳转指定章节
本文将介绍使用 Python 编写一个简单的文本阅读器,可以读取 txt 文档并跳到指定的章节。
代码示例
def read_book(file_path):
with open(file_path, 'r') as file:
content = file.read()
return content
def find_chapter(content, chapter):
chapters = content.split('CHAPTER')
if chapter <= len(chapters):
return chapters[chapter]
else:
return 'Chapter not found.'
# 读取 txt 文档
file_path = 'book.txt'
book_content = read_book(file_path)
# 输入要跳转的章节
chapter_number = int(input('Enter chapter number: '))
# 查找指定章节
chapter_content = find_chapter(book_content, chapter_number)
# 打印指定章节内容
print(chapter_content)
代码说明
read_book(file_path)函数:读取指定路径的 txt 文档内容,并返回文本内容。find_chapter(content, chapter)函数:将文本内容按照 'CHAPTER' 分隔符进行分割,并根据传入的章节号返回对应章节的内容。如果章节号超出范围,则返回 'Chapter not found.'- 主程序部分:
- 获取 txt 文档路径
file_path,并调用read_book()函数读取文本内容。 - 从用户输入获取要跳转的章节号
chapter_number。 - 调用
find_chapter()函数查找指定章节内容。 - 打印指定章节的内容。
- 获取 txt 文档路径
注意事项
- 该代码示例假设 txt 文档中的章节以 'CHAPTER' 作为分隔符。如果你的 txt 文档中的章节标记不同,你需要相应地修改
find_chapter函数中的分隔符。 - 需要将
file_path变量设置为你的 txt 文档的路径。 - 在运行代码之前,请确保你的 txt 文档存在并且可读。
扩展
你可以根据需要对代码进行扩展,例如:
- 添加目录显示功能,方便用户选择章节。
- 添加书签功能,方便用户记录阅读进度。
- 添加搜索功能,方便用户查找特定内容。
希望本文对你有所帮助!
原文地址: https://www.cveoy.top/t/topic/fOfD 著作权归作者所有。请勿转载和采集!