用Python给宝宝写一个故事机
运行环境及其说明
-
Windows
-
Python3.6以上
-
可以朗读中文
需要安装的库
+ pypiwin32(用于朗读)
pip install pypiwin32
+ pandas(用于记录上一次阅读位置)
pip install pandas
+ linecache(读取文本文件的指定行)
pip install linecache
程序如下
"""
Create on Jan-30-2020
Author:CC
Evn:Python3.6
Only test on windows10
"""
import os, pandas as pd, linecache as lch, win32com.client
class cachefile:
"""
Read specific line of a txt
"""
def __init__(self, file_path):
self.max_line = len(lch.getlines(file_path))
self.file_path = file_pathdef getline(self, num):
if 0 <= num <= self.max_line:
return lch.getline(self.file_path, num).strip()
else:
raise ValueError
def speak(in_str):
"""
Speak out a input string using system API
:param in_str:String object
:return:None
"""
speak_out = win32com.client.Dispatch('SAPI.SPVOICE')
speak_out.Speak(in_str)
def read_line(num, story_file, record_file):
"""
Speak out line whitch read from a txt file
:param num: Line number
:param strory_file: strory_file path
:param record_file: record_file path
:return:
"""
try:
line = story_file.getline(num)
except ValueError:
line = '已经是文本的最后一行,朗读结束。'
print(line_num, line)
speak(line)
return -1
print(line_num, line)
speak(line)
pd.DataFrame([{'line_num': num + 1}]).to_csv(record_file, index=False)
return num + 1
if __name__ == '__main__':
path = r'C:\Users\a\Downloads'
# this is a story
story_file = rf'{path}\伊索寓言.txt'
# this file record the last time position
record_file = rf'{path}\record_file.csv'
# create the record file if record_file does not exist
if os.path.exists(record_file):
line_num = pd.read_csv(record_file)['line_num'][0]
else:
line_num = 0
pd.DataFrame([{'line_num': 0}]).to_csv(record_file, index=False)
file_read = cachefile(story_file)
while 1:
line_num = read_line(num=line_num, story_file=file_read, record_file=record_file)
if line_num == -1:
break
[Python,Pandas,SQL,ETL]交流群 164142295
本文介绍如何使用Python在Windows环境下为宝宝创建一个故事机,利用pypiwin32库进行语音朗读,Pandas记录阅读位置,linecache读取文本特定行。程序读取指定txt文件,逐行朗读,并更新进度记录。
5772

被折叠的 条评论
为什么被折叠?



