1.实现python文本写入word
准备我测试使用的Python版本为2.7.10,如果你的版本是Python3.5的话,这里就不太适合了。
使用Speech API原理我们的想法是借助微软的语音接口,所以我们肯定是要进行调用 相关的接口。所以我们需要安装pywin32来帮助我们完成这一个底层的交互。
示例代码import win32com.clientspeaker = win32com.client.Dispatch("SAPI.SpVoice")speaker.Speak("Hello, it works!")小总结是的,调用接口来实现语音功能就是这么简单,但是我们不得不来聊一聊这种方式的缺点。对中文支持的不够好,仅仅是这一点,估计在中国没几个用它的了。
还有就是语速不能很好的控制pyttsx方式原理pyttsx 是Python的一个关于文字转语音方面的很不错的库。我们还可以借助pyttsx来实现在线朗读rfc文件或者本地文件等等,最为关键的是,它对中文支持的还是不错的。
示例代码# coding:utf-8import sysreload(sys)sys.setdefaultencoding('utf8')# __author__ = '郭 璞'# __date__ = '2016/8/6'# __Desc__ = 文字转语音输出import pyttsxengine = pyttsx.init()engine.say('hello world')engine.say('你好,郭璞')engine.runAndWait()# 朗读一次engine.endLoop()小总结使用pyttsx,我们可以借助其强大的API来实现我们基本的业务需求。很酷吧。
pyttsx深入研究做完上面的小实验,你肯定会觉得怎么这么不过瘾呢? 别担心,下面我们就一起走进pyttsx的世界,深入的研究一下其工作原理吧。语音引擎工厂类似于设计模式中的“工厂模式”,pyttsx通过初始化来获取语音引擎。
当我们第一次调用init操作的时候,会返回一个pyttsx的engine对象,再次调用的时候,如果存在engine对象实例,就会使用现有的,否则再重新创建一个。pyttsx.init([driverName : string, debug : bool]) → pyttsx.Engine从方法声明上来看,第一个参数指定的是语音驱动的名称,这个在底层适合操作系统密切相关的。
如下:1.drivename:由pyttsx.driver模块根据操作系统类型来调用,默认使用当前操作系统可以使用的最好的驱动sapi5 - SAPI5 on Windowsnsss - NSSpeechSynthesizer on Mac OS Xespeak - eSpeak on every other platform2.debug: 这第二个参数是指定要不要以调试状态输出,建议开发阶段设置为True引擎接口要想很好的运用一个库,不了解其API是不行的。下面来看看pyttsx。
engine.Engine的引擎API。方法签名 参数列表 返回值 简单释义 connect(topic : string, cb : callable) topic:要描述的事件名称;cb:回调函数 → dict 在给定的topic上添加回调通知 disconnect(token : dict) token:回调失联的返回标记 Void 结束连接 endLoop() None → None 简单来说就是结束事件循环 getProperty(name : string) name有这些枚举值“rate, vioce,vioces,volumn → object 获取当前引擎实例的属性值setProperty(name : string) name有这些枚举值“rate, vioce,vioces,volumn → object 设置当前引擎实例的属性值 say(text : unicode, name : string) text:要进行朗读的文本数据; name: 关联发音人,一般用不到 → None 预设要朗读的文本数据,这也是“万事俱备,只欠东风”中的“万事俱备” runAndWait() None → None 这个方法就是“东风”了。
当事件队列中事件全部清空的时候返回 startLoop([useDriverLoop : bool]) useDriverLoop:是否启用驱动循环 → None 开启事件队列 元数据音调在pyttsx.voice.Voice中,处理合成器的发音。age 发音人的年龄,默认为Nonegender 以字符串为类型的发音人性别: male, female, or neutral.默认为Noneid 关于Voice的字符串确认信息. 通过 pyttsx.engine.Engine.setPropertyValue()来设置活动发音签名. 这个属性总是被定义。
languages 发音支持的语言列表,如果没有,则为一个空的列表。name 发音人名称,默认为None.更多测试朗读文本import pyttsxengine = pyttsx.init()engine.say('Sally sells seashells by the seashore.')engine.say('The quick brown fox jumped over the lazy dog.')engine.runAndWait()事件监听import pyttsxdef onStart(name): print 'starting', namedef onWord(name, location, length): print 'word', name, location, lengthdef onEnd(name, completed): print 'finishing', name, completedengine = pyttsx.init()engine.say('The quick brown fox jumped over the lazy dog.')engine.runAndWait()打断发音import pyttsxdef onWord(name, location, length): print 'word', name, location, length if location > 10: engine.stop()engine = pyttsx.init()engine.say('The quick brown fox jumped over the lazy dog.')engine.runAndWait()更换发音人声音engine = pyttsx.init()voices = engine.getProperty('voices')for voice in voices: engine.setProperty('voice', voice.id) engine.say('The quick brown fox jumped over the lazy dog.')engine.runAndWait()语速控制engine = pyttsx.init()rate = engine.getProperty('rate')engine.setProperty('rate', rate+50)engine.say('The quick brown fox jumped over the lazy dog.')engine.runAndWait()音量控制engine = pyttsx.init()volume = engine.getProperty('volume')engine.setProperty('volume', volume-0.25)engine.say('The quick brown fox jumped over th。
2.python如何读取word文件
>> def PrintAllParagraphs(doc):
count=doc.Paragraphs.Count
for i in range(count-1,-1,-1):
pr=doc.Paragraphs[i].Range
print pr.Text
>>> app=my.Office.Word.GetInstance()
>>> doc=app.Documents[0]
>>> PrintAllParagraphs(doc)
1.什么是域
域应用基础
>>> @staticmethod
def GetInstance():
u'''获取Word应用程序的Application对象'''
import win32com.client
return win32com.client.Dispatch('Word.Application')1. my.Office.Word.GetInstance的方法实现如上,是一个使用win32com操纵Word Com的接口的封装
2. 所有Paragraph即段落对象,都是通过Paragraph.Range.Text来访问它的文字的
3.看到网上说的Pywin32可以像VC一样的形式来使用PYTHON开发win
不能画界面。说它跟VC一样是因为可以它也是个集成开发环境。
如果你还不大会python,建议先学好python再来想界面的事情。
如果你已经很熟悉python了,可以考虑用pyqt开发图形界面。pyqt是对qt的python封装,你要学会用它最好先学会用qt。qt的文档大部分是英文的,中文也有但相对比较少,自己慢慢看吧。
虽然现在编程比10年前要容易很多,但还是有一定门槛,有兴趣就自己多花时间学学钻研下,没兴趣就改行干别的吧。做程序员性价比不高。
4.python操作word文档,用win32com,如何用python中的变量来命名
import sys, time, string, win32com.client, stat, osclass CWordAutomate: """封装word com 连接""" def __init__( self ): """创建到word的ole连接对象""" self.m_obWord = win32com.client.Dispatch( "Word.Application" ) self.m_obDoc = self.m_obWord.Documents.Add( ) #创建文档 self.m_obWord.Visible = 1 self.m_Sel = self.m_obWord.Selection # 获取选择对象 def WriteLine( self, sTxt, sFont, lSize, bBold=0 ): """写一行到文档""" self.m_Sel.Font.Name = sFont self.m_Sel.Font.Bold = bBold self.m_Sel.Font.Size = lSize self.m_Sel.TypeText( Text=sTxt + "\n" ) def Save(self, sFilename): self.m_obDoc.SaveAs(sFilename) def Quit(self): self.m_obWord.Quit()def file_test(file): """ 测试用户提供的文件,查看它是否存在并包含数据。
如果输入文件不存在或是空的,则返回一个警告代码 """ if (0 == os.path.isfile(file) or (0 == os.stat(file)[stat.ST_SIZE])): return 1 else: return 0if __name__ == "__main__": usage = "\n\n\tUsage: msword.py {inputfile} {outputfile}\n" # # 测试传入数字的参数 # if len(sys.argv) != 3: print "\n\n\tmsword.py error: \n\n\tInsufficient arguments passed." print usage sys.exit(1) # 测试源文件是否存在并包含数据 if file_test(sys.argv[1]) == 1 : print "\n\n\tmsword.py error: \n\n\tSource file not found or is empty." print usage sys.exit(1) # 测试目标文件,避免意外导致崩溃 if file_test(sys.argv[2]) == 0 : print "\n\n\tmsword.py error: \n\n\tTarget file already exists." print usage sys.exit(1) sFileName = sys.argv[1] obFile = file( sFileName, 'r+' ) sContent = obFile.read() obFile.close() lstContent = sContent.splitlines() # # 写入数据 # obWord = CWordAutomate() for sLine in lstContent: obWord.WriteLine( sLine, "Courier New", 10 ) sLastMsg = time.strftime( "document generated on %c", time.localtime() ) obWord.WriteLine( sLastMsg, "Times New Roman", 14, 0 ) obWord.Save(sys.argv[2]) obWord.Quit()。
5.python pywin32 处理Excel如何添加某个单元格背景颜色
#Win32#打开EXCEL
WinApp = win32com.client.DispatchEx('Excel.Application')
#要处理的excel文件路径#out.file是文件 绝对路径
WinBook = WinApp.Workbooks.Open(out_file)
#要处理的excel页
WinSheet = WinBook.Worksheets('Sheet1')
#单元格添加颜色
WinSheet.Cells(1, 1).Interior.ColorIndex = 3
#或者Range("A1")
WinSheet.Range("A1").Interior.ColorIndex = 3
#3=红色,不同的值代表不同的颜色,可以去查看msdn vba 文档,这就不详细说了
#再是RGB调色方式#Cells 和 Range都可以,Range可以选择一大片区域
WinSheet.Cells(1, 1).Interior.Color = RGB(0, 0, 255)
#或
WinSheet.Range("A1").Interior.Color = RGB(255, 0, 255)
#字体的颜色也是一样
WinSheet.Cells(1, 1).Font.ColorIndex = 3
WinSheet.Cells(1, 1).Font.Color = RGB(0, 0, 255)
6.python读取word文档内容
import fnmatch, os, sys, win32com.client readpath=r'D:\123' wordapp = win32com.client.gencache.EnsureDispatch("Word.Application") try: for path, dirs, files in os.walk(readpath): for filename in files: if not fnmatch.fnmatch(filename, '*.docx'):continue doc = os.path.abspath(os.path.join(path,filename)) print 'processing %s。
' % doc wordapp.Documents.Open(doc) docastext = doc[:-4] + 'txt' wordapp.ActiveDocument.SaveAs(docastext,FileFormat=win32com.client.constants.wdFormatText) wordapp.ActiveDocument.Close() finally: wordapp.Quit() print 'end' f=open(r'd:\123\test.txt','r') for line in f.readlines(): print line.decode('gbk') f.close()。
转载请注明出处51数据库 » pywin32word格式