python操作word文档
A. 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
= 22
wdFormatHTML = 8
wdFormatPDF = 17
wdFormatRTF = 6
wdFormatTemplate = 1
wdFormatTemplate97 = 1
wdFormatText = 2
wdFormatTextLineBreaks = 3
wdFormatUnicodeText = 7
wdFormatWebArchive = 9
wdFormatXML = 11
wdFormatXMLDocument = 12
= 13
wdFormatXMLTemplate = 14
= 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)
#不要(),容易引起歧义。
B. 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()
C. python如何读取word文件中的文本内容并写入到新的txt文件
D. python操作word文档表格
>>>app=my.Office.Word.GetInstance()
>>>doc=app.Documents[0]
>>>printdoc.Name
VBA工具集.doc
>>>doc.Tables.Count
2
>>>table=doc.Tables[1]
>>>table.Cell(1,1).Select()
>>>app.Selection.MoveEnd(Unit=12,Count=4)
4
>>>app.Selection.Cells.Shading.Texture=-10
>>>
1.my.Office.Word.GetInstance()用win32com得到Word的Application对象的实例
2.我所使用的样本word文件中包含两个Table第二个Table是想要修改的
3.table.Cell(1,1).Select()用于选中这个样表的第一个单元格
4.app.Selection.MoveEnd用于获得向右多选取4个单元格,wdCell=12,用于指示按单元格移动
5.app.Selection.Cells.Shading.Texture = -10用于执行阴影底纹的设置工作,wdTextureDiagonalUp=-10是一个代表斜向右上的底纹样式的常数
E. 如何用Python编写代码在Word中实现带公式计算过程的计算书
1、打开idle。点击file,然后点击new file 这是创建一个新的文件。新建...
答:1、打开idle。点击file,然后点击new file.这是创建一个新的文件。 新建一个文件之后,我们输入第一行代码,使用print函数,在屏幕上打印一句话,其中字符串要使用双引号,输入法要使用英文输入法,如果符号使用中文输入法输入,就会出现错误。p...
2020-11-17回答者:环球青藤1个回答
pythonsympy中生成的公式怎么粘到word里
答:右键选 show math as→mathML Code 全选复制,在word中右键以文本形式粘贴
2018-01-27回答者:夜歌在路上2个回答
如何使用python提取并处理word文档中插入的mathtyp...
答:我没做过,只能提供大概思路给你。这是mathtype的SDK:,里面关于API的描述: MathType API Documentation The MathType API allows you to call functions used by the MathType Commands ForWord. On Windows, this API is split between MathP...
2017-10-03回答者:天天不看java1个回答
如何用python写这个代码
问:使用两个参数定义一个名为dictionaryToListOfValues的函数。 此函数的第...
答:使用Python自带的IDLE 在开始-->程序-->Python2.5(视你安装的版本而不同)中找到IDLE(Python GUI)。 点击后弹出如下窗体: 1,在>>>提示符后输入代码,回车,就可以执行此代码。 IDLE支持语法高亮,支持自动缩进,支持方法提示,不过提示的很慢。...
2019-10-17回答者:司马刀剑2个回答3
如何用python编写计算器
答:我想你的需求应该是一个图形界面的程序,而不是简单的在命令行上输入。 那么,要做的第一件事就是选择一个图形界面套件。可以使用原生的TK,也可以用跨平台性能很好的wxPython,或者是整体结构很像MFC的PyWin32。至于pyGTK,pyQT,都是可选的,但...
2011-05-30回答者:碧蓝右耳3个回答6
用Python编写代码1×2×3+4×5×6+7×8×9+++···99×100×1...
答:t=1 for i in range(1,102): t*=i print(t)
2020-04-05回答者:知道网友1个回答2
python如何识别docx中的公式
答: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(fi...
2016-07-09回答者:知道网友1个回答2
如何用Python代码运行Word中的VBA
问:请问有什么好的办法用Python代码运行Word中的VBA吗, 具体需要import哪...
答:安装pypiwin32 import win32com.client app= win32com.client.Dispatch("word.Application") app.Workbooks.Open("宏代码所在文件路径") app.Application.Run("宏名称") app.Application.Quit()
2019-08-31回答者:娘化的新世界1个回答
用Python写一个,两个数的加,减,乘,除的函数,...
答:我课程中的部分代码(除没写): def f_add(a,b): return a+bdef f_mul(a,b): return a*bdef f_sub(a,b): return a-b def g1(f,a,b): return f(a,b)a,b,c,d = 1,2,3,4print g1(f_sub, g1(f_mul, g1(f_add,a,b), c), d), g1(f_mul, g1(f_add,a,b)...
2017-11-21回答者:黑板客1个回答4
python编写2个函数代码,实现求最小公倍数和最大公...
问:使用两个函数实现,最小公倍数和最大公约数
答:def gcd(a, b): # 求最大公约数 x = a % b while (x != 0): a, b = b, x x = a % b return bdef lcm(a,b): # 求最小公倍数 return a*b//gcd(a,b) 程序缩进如图所示
F. python如何读取word文件
>>>defPrintAllParagraphs(doc):
count=doc.Paragraphs.Count
foriinrange(count-1,-1,-1):
pr=doc.Paragraphs[i].Range
printpr.Text
>>>app=my.Office.Word.GetInstance()
>>>doc=app.Documents[0]
>>>PrintAllParagraphs(doc)
1.什么是域
域应用基础
>>>
@staticmethod
defGetInstance():
u'''获取Word应用程序的Application对象'''
importwin32com.client
returnwin32com.client.Dispatch('Word.Application')
my.Office.Word.GetInstance的方法实现如上,是一个使用win32com操纵Word Com的接口的封装
所有Paragraph即段落对象,都是通过Paragraph.Range.Text来访问它的文字的
G. 如何用python读取word
使用Python的内部方法open()读取文本文件
try:
f=open('/file','r')
print(f.read())
finally:
iff:
f.close()
如果读取word文档推荐使用第三方插件,python-docx 可以在官网上下载
使用方式
#-*-coding:cp936-*-
importdocx
document=docx.Document(文件路径)
docText=' '.join([
paragraph.text.encode('utf-8')forparagraphindocument.paragraphs
])
printdocText
H. python操作word文档,如何合并单元格
>>>app=my.Office.Word.GetInstance()
>>>doc=app.Documents[0]
>>>table=doc.Tables[1]
>>>table.Cell(1,1).Select()
>>>app.Selection.MoveDown(Unit=5,Count=2,Extend=1)
>>>app.Selection.Cells.Merge()
>>>
my.Office.Word.GetInstance()用win32com得到Word的Application对象的实例
我所使用的样本word文件中包含两个Table第二个Table是想要修改的
table.Cell(1,1).Select()用于选中这个样表的第一个单元格
app.Selection.MoveDown用于获得向下多选取3个单元格
app.Selection.Cells.Merge()用于执行合并工作
I. python word文件处理
#-*- 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()
J. python处理word文档
有个库叫‘Python-docx’
安装之后 python 可以读写 word 文档,就可以拼接了。