用Python给宝宝写一个故事机(语音朗读)

本文介绍如何使用Python在Windows环境下为宝宝创建一个故事机,利用pypiwin32库进行语音朗读,Pandas记录阅读位置,linecache读取文本特定行。程序读取指定txt文件,逐行朗读,并更新进度记录。

用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_path

    def 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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值