上次学习爬取小说保存到txt文本文件,方便离线阅读,现在做一个简易TXT文本小说阅读器,支持手动翻页和自动翻页阅读。
废话不多说,直接上代码,实践下。
read_txt.py:
- import time
-
-
- def read_txt_book(file_path, start_str, per_line=3, auto_flag=False, sleep_time=3):
- '''
- @方法名称: TXT文本小说阅读器
- @中文注释: 读取txt文本工具,自动,手动翻页
- @入参:
- @param file_path str 文件路径
- @param start_str str 开始读取字符串
- @param per_line int 每次读取行数
- @param auto_flag bool 是否自动翻页
- @param sleep_time int 自动翻页休眠时间(秒)
- @出参:
- @返回状态:
- @return 0 失败或异常
- @return 1 成功
- @返回错误码
- @返回错误信息
- @param rsp_dict dict 响应容器
- @作 者: PandaCode辉
- @创建时间: 2023-09-08
- @使用范例: read_book('1.txt')
- '''
-
- try:
- if (not type(file_path) is str):
- return [0, "111111", "文件路径参数类型错误,不为字符串", [None]]
- if (not type(start_str) is str):
- return [0, "111112", "开始读取字符串参数类型错误,不为字符串", [None]]
-
- with open(file_path, mode='r', encoding="utf-8") as f:
- '''
- seek() 函数用于移动文件指针到文件的指定位置
- f.seek(offset, whence), f指的是file(或$你的文件名)
- Parameters:
- offset: 将光标向前移动n个位置
- whence: 参考位置,一般参数为0, 1, 2
- 0 :将开头作为参考位置
- 1 :将当前作为参考位置
- 2 :将末尾作为参考位置
- '''
- f.seek(0, 2)
- # tell() 函数用于判断文件指针当前所处的位置
- # 读取文章最末尾的光标位置
- end_position = f.tell()
- print(end_position)
- # 将光标移动到文件的开头
- f.seek(0, 0)
- # 开始读取字符串不为空
- if start_str != "":
- line_position = 0
- while True:
- line = f.readline()
- line_position += 1
- if start_str in line:
- print(f"第 {line_position} 行,内容为:{line.strip()}")
- break
- # 读取文章当前的光标位置
- now_position = f.tell()
- # 判断光标是否到文章最末尾
- if now_position == end_position:
- print('已读完')
- break
- # 判断是否自动阅读模式
- if auto_flag:
- while True:
- for i in range(per_line):
- print(f.readline(), end='')
- # 读取文章当前的光标位置
- now_position = f.tell()
- # 判断光标是否到文章最末尾
- if now_position == end_position:
- print('已读完')
- break
- else:
- # 休眠时间-3秒
- time.sleep(sleep_time)
- else:
- while True:
- # 读取文章当前的光标位置
- now_position = f.tell()
- # 判断光标是否到文章最末尾
- if now_position == end_position:
- print('已读完')
- break
- else:
- # 翻页提示符
- num_next = input('输入n翻下一页:')
- if num_next == 'n':
- for j in range(per_line):
- print(f.readline(), end='')
- else:
- print('输入错误,请重新输入')
- # 返回容器
- return [1, '000000', '读取txt文本工具', [None]]
-
- except Exception as e:
- print("读取txt文本工具异常," + str(e))
- return [0, '999999', "读取txt文本工具异常," + str(e), [None]]
-
-
- # 查找文本文件中的指定字符串,若存在,输出所在的函数
- # file_path ———— 文本文件路径
- # string ———— 指定要查找的字符串
- def TextFileSearch(file_path, start_str):
- with open(file_path, 'r', encoding='utf-8') as f:
- line_position = 0
- for line in f.readlines():
- line_position += 1
- if start_str in line:
- print(f"第 {line_position} 行,内容为:{line.strip()}")
- break
-
-
- # 主方法
- if __name__ == '__main__':
- file_path = '重生八八从木匠开始.txt'
- start_str = '第392章'
- # 查找文本文件中的指定字符串位置
- # TextFileSearch(file_path, start_str)
- # 读取txt文本工具
- read_txt_book(file_path, start_str, auto_flag=True)