#-*- encoding: utf8 -*-
import win32com
from win32com.client import Dispatch, constants
import win32com.client
import __main__
import os
import new
import sys
import re
import string
reload(sys)
sys.setdefaultencoding('utf8')
#from fileinput import filename
class Word(object):
#初始化word对象
def __init__(self, uri):
self.objectword(uri)
#创建word对象
def objectword(self,url):
self.word = win32com.client.Dispatch('Word.Application')
self.word.Visible = 0
self.word.DisplayAlerts = 0
self.docx = self.word.Documents.Open(url)
self.wrange = self.docx.Range(0, 0)
#关闭word
def close(self):
self.word.Documents.Close()
self.word.Quit()
#创建word
def create(self):
pass
#在word中进行查找
def findword(self, key):
question = []
uri = r'E:\XE\ctb.docx'
self.objectword(uri)
#读取所有的word文档内容
range = self.docx.Range(self.docx.Content.Start,self.docx.Content.End)
question = str(range).split("&")
#查找内容
#question = re.split(r"(\r[1][0-9][0-9]+.)",str(range))
#l = question[0].split("\d+.")
for questionLine in question:
questionLine = questionLine.strip('\n')
l = re.split(r"([1][0-9][0-9]+.)",questionLine)
del l[0]
for t in l:
s = str(key[0:3])
if str(t).find(s) > -1:
#插入
g = string.join(l)
print g.encode('gb2312')
#print g.decode("")
self.insertword(g)
print "sss"
else:
print "ttt"
#插入word
def insertword(self,w):
url = r'E:\XE\ctb.doc'
self.objectword(url)
self.wrange.InsertAfter(w)
pass
#读取数据源
def source(self, src):
f = open(src)
d = f.readlines()
for l in d:
name, question01, question02, question03, question04, question05 = tuple(l.decode('utf8').split('\t'))
if question01 != u'全对':
#self.wrange.InsertAfter(name)
self.findword(question01)
return self
Word(r'E:\XE\xx.docx').source(r'E:\XE\xe.txt').close()
如何在mac上用python批量将word文件转成txt文件
Word 文档本质上是压缩后的资源文件与 xml 文件,可以根据 Open XML 标准去解析 xml 文件。要是嫌麻烦,用 python-docx 库似乎也可以完成这个。
求写一段python处理word文件的批处理命令。
python支持使用com技术调用word,但是不能直接操纵word文件,因为word文件是私有格式。所以你说的正则表达式查找替换,如果word本身不支持,那就没有办法了
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()
能否直接读取word文档内容吗?
我在其他地方也看到了先将word保存为txt再读取,为何要这样操作那?
因为word并不是纯文本(不存在一行一行的概念),尽管你可能只输入了文本,但不能认为它就是文本
python能打开word文档吗
首先下载安装win32com
from win32com import client as wc
word = wc.Dispatch('Word.Application')
doc = word.Documents.Open('c:/test')
doc.SaveAs('c:/test.text', 2)
doc.Close()
word.Quit()
这种方式产生的text文档,不能用python用普通的r方式读取,为了让python可以用r方式读取,应当写成
doc.SaveAs('c:/test', 4)
注意:系统执行完成后,会自动产生文件后缀txt(虽然没有指明后缀)。
在xp系统下面,应当,
open(r'c:\text','r')
wdFormatDocument = 0
wdFormatDocument97 = 0
wdFormatDocumentDefault = 16
wdFormatDOSText = 4
wdFormatDOSTextLineBreaks = 5
wdFormatEncodedText = 7
wdFormatFilteredHTML = 10
wdFormatFlatXML = 19
wdFormatFlatXMLMacroEnabled = 20
wdFormatFlatXMLTemplate = 21
wdFormatFlatXMLTemplateMacroEnabled = 22
wdFormatHTML = 8
wdFormatPDF = 17
wdFormatRTF = 6
wdFormatTemplate = 1
wdFormatTemplate97 = 1
wdFormatText = 2
wdFormatTextLineBreaks = 3
wdFormatUnicodeText = 7
wdFormatWebArchive = 9
wdFormatXML = 11
wdFormatXMLDocument = 12
wdFormatXMLDocumentMacroEnabled = 13
wdFormatXMLTemplate = 14
wdFormatXMLTemplateMacroEnabled = 15
wdFormatXPS = 18
照着字面意思应该能对应到相应的文件格式,如果你是office
2003可能支持不了这么多格式。word文件转html有两种格式可选wdFormatHTML、wdFormatFilteredHTML(对应数字
8、10),区别是如果是wdFormatHTML格式的话,word文件里面的公式等ole对象将会存储成wmf格式,而选用
wdFormatFilteredHTML的话公式图片将存储为gif格式,而且目测可以看出用wdFormatFilteredHTML生成的HTML
明显比wdFormatHTML要干净许多。
当然你也可以用任意一种语言通过com来调用office API,比如PHP.
from win32com import client as wc
word = wc.Dispatch('Word.Application')
doc = word.Documents.Open(r'c:/test1.doc')
doc.SaveAs('c:/test1.text', 4)
doc.Close()
import re
strings=open(r'c:\test1.text','r').read()
result=re.findall('\(\s*[A-D]\s*\)|\(\xa1*[A-D]\xa1*\)|\(\s*[A-D]\s*\)|\(\xa1*[A-D]\xa1*\)',strings)
chan=re.sub('\(\s*[A-D]\s*\)|\(\xa1*[A-D]\xa1*\)|\(\s*[A-D]\s*\)|\(\xa1*[A-D]\xa1*\)','()',strings)
question=open(r'c:\question','a+')
question.write(chan)
question.close()
answer=open(r'c:\answeronly','a+')
for i,a in enumerate(result):
m=re.search('[A-D]',a)
answer.write(str(i+1)+' '+m.group()+'\n')
answer.close()
chan=re.sub(r'\xa3\xa8\s*[A-D]\s*\xa3\xa9','()',strings)
#不要(),容易引起歧义。
实现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 Windows
nsss - NSSpeechSynthesizer on Mac OS X
espeak - eSpeak on every other platform
2.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
发音人的年龄,默认为None
gender
以字符串为类型的发音人性别: male, female, or neutral.默认为None
id
关于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 the lazy dog.')engine.runAndWait()
执行一个事件驱动循环
engine = pyttsx.init()def onStart(name): print 'starting', namedef onWord(name, location, length): print 'word', name, location, lengthdef onEnd(name, completed): print 'finishing', name, completed if name == 'fox': engine.say('What a lazy dog!', 'dog') elif name == 'dog': engine.endLoop()engine = pyttsx.init()engine.say('The quick brown fox jumped over the lazy dog.', 'fox')engine.startLoop()
使用一个外部的驱动循环
engine = pyttsx.init()engine.say('The quick brown fox jumped over the lazy dog.', 'fox')engin(www.alOnely.Com.Cn)e.startLoop(False)# engine.iterate() must be called inside externalLoop()externalLoop()engine.endLoop()
总结
以上就是Python如何实现文本转语音的全部内容,看完了上面的讲述,是不是感觉Python实现文本转语音还是蛮简单的?那么,大家快来尝试尝试吧。希望本文对大家学习Python有所帮助。
如何使用python将pdf文件改成word文件
用软件,使用之后然后有两种结果
1、转化出来的就是想要的word,这种情况最理想了;
2、转化出来的word上都是图片,需要上网找“ABBYY finereader v9”一类的文字识别软件。ABBYY finereader v9是我见过的最强大的PDF(图片格式或者是扫描件)转word的软件。它是一款OCR软件,界面比较简洁明,9.0和以上版本有简体中文版的,支持100语言的识别,特别是混合多种语言识别效果也非常好:安装完毕之后,首先把图片上的文字识别出来,然后再对照图片把识别错误的地方改过来,这样就实现了,从JPEG文件到word的格式转换。
这一类的软件有PDF To Word Converter、Solid converter PDF等,大致过程都是一样的。
也可以在线联网将PDF转为word文件,但是存在泄密的可能性,因此不建议使用。
如何在mac上用python批量将word文件转成txt文件 / 网络技术编程
python实现起来可能没有现成解决方案。因为py库可能没有全面的office套件解析器。
mac想批量转,很容易。
安装openoffice。
终端执行 soffice --headless --convert-to txt my_file.doc/.docx
如果批量将当前目录下所有doc转为txt,则写过简单shell:
for i in `ls *doc`; do soffice --headless --convert-to txt $i ; done; 即可。
以上同时适用linux。
转载请注明出处51数据库 » pythonwordtxt pythonword文件处理