拖放WORD文件朗读全文

把WORD拖放到tkinter的窗口,就可以朗读整改word文件的内容。

代码:

python 复制代码
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 17:09:35 2024

@author: YBK
"""
import pyttsx3
import comtypes.client
import os
import tkinter as tk
import windnd
from tkinter.messagebox import showinfo

def get_file_extension(file_path):
    return os.path.splitext(file_path)[-1]

def read_doc_file(file_path):
    # 创建一个Word应用程序对象
    word = comtypes.client.CreateObject('Word.Application')
    word.Visible = 0  # 不显示Word界面
 
    # 打开Word文档
    doc = word.Documents.Open(file_path)
 
    # 读取文档内容
    for paragraph in doc.Paragraphs:
        # 声明文本
        text = paragraph.Range.Text
        # 执行朗读
        engine.say(text)
        engine.runAndWait()
    # 关闭文档并退出Word应用程序
    doc.Close()
    word.Quit()

def dragged_files(files):
    fileurl = ''
    if len(files) > 1:
        # 这里想使用os.path.splitext(fileurl)[1] == '.doc' 但发现wps也能朗读
        showinfo("提示","请拖放一个WORD文件!")
    else:
        print(files[0].decode('gbk'))
        fileurl = files[0].decode('gbk')
    read_doc_file(fileurl)
    
if __name__ == '__main__':
    # 初始化tts引擎
    engine = pyttsx3.init()     
    # 设置声音对象
    voices = engine.getProperty('voices')
    engine.setProperty('voice', voices[0].id)  # 可以通过修改索引来更换声音     
    # 设置语速
    rate = engine.getProperty('rate')
    engine.setProperty('rate', 220)     
    # 设置音量
    volume = engine.getProperty('volume')
    engine.setProperty('volume', volume)
    rootWindow = tk.Tk()
    rootWindow.title("拖放WORD文件朗读全文")
    rootWindow.geometry("300x120")
    windnd.hook_dropfiles(rootWindow , func=dragged_files)
    rootWindow.mainloop()

要注意word文件没有被打开。

相关推荐
杜子不疼.17 分钟前
PyPTO:面向NPU的高效并行张量编程范式
开发语言
lly20240618 分钟前
C# 结构体(Struct)
开发语言
YMWM_29 分钟前
python3继承使用
开发语言·python
大空大地202639 分钟前
表达式与运算符
c#
Once_day44 分钟前
C++之《程序员自我修养》读书总结(1)
c语言·开发语言·c++·程序员自我修养
喜欢喝果茶.1 小时前
QOverload<参数列表>::of(&函数名)信号槽
开发语言·qt
亓才孓1 小时前
[Class类的应用]反射的理解
开发语言·python
努力学编程呀(๑•ี_เ•ี๑)1 小时前
【在 IntelliJ IDEA 中切换项目 JDK 版本】
java·开发语言·intellij-idea
向上的车轮1 小时前
为什么.NET(C#)转 Java 开发时常常在“吐槽”Java:checked exception
java·c#·.net