如何用python读取word
使用Python的内部方法open()读取文本文件 try: f=open('/file','r') print(f.read())finally: if f: f.close()如果读取word文档推荐使用第三方插件,python-docx 可以在官网上下载 使用方式 # -*- coding: cp936 -*-import docxdocument = docx.Document(文件路径)docText = '\n\n'.join([ paragraph.text.encode('utf-8') for paragraph in document.paragraphs])print docText...
python如何获取word文件中某个关键字之后的表格
最好是全部都读取到程序中,在程序中进行判断。
本文实例讲述了Python实现批量读取word中表格信息的方法。
分享给大家供大家参考。
具体如下:单位收集了很多word格式的调查表,领导需要收集表单里的信息,我就把所有调查表放一个文件里,写了个python小程序把所需的信息打印出来#coding:utf-8import osimport win32comfrom win32com.client import Dispatch, constantsfrom docx import Documentdef parse_doc(f):"""读取doc,返回姓名和行业"""doc = w.Documents.Open( FileName = f )t = doc.Tables[0] # 根据文件中的图表选择信息name = t.Rows[0].Cells[1].Range.Textsituation = t.Rows[0].Cells[5].Range.Textpeople = t.Rows[1].Cells[1].Range.Texttitle = t.Rows[1].Cells[3].Range.Textprint name, situation, people,titledoc.Close()def parse_docx(f):"""读取docx,返回姓名和行业"""d = Document(f)t = d.tables[0]name = t.cell(0,1).textsituation = t.cell(0,8).textpeople = t.cell(1,2).texttitle = t.cell(1,8).textprint name, situation, people,titleif __name__ == "__main__":w = win32com.client.Dispatch('Word.Application')# 遍历文件PATH = "H:\work\\aaa" # windows文件路径doc_files = os.listdir(PATH)for doc in doc_files:if os.path.splitext(doc)[1] == '.docx':try:parse_docx(PATH+'\\'+doc)except Exception as e:print eelif os.path.splitext(doc)[1] == '.doc':try:parse_doc(PATH+'\\'+doc)except Exception as e:print e希望本文所述对大家的Python程序设计有所帮助。
python能打开word文档吗
首先下载安装win32comfrom win32com import client as wcword = 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 = 0wdFormatDocument97 = 0wdFormatDocumentDefault = 16wdFormatDOSText = 4wdFormatDOSTextLineBreaks = 5wdFormatEncodedText = 7wdFormatFilteredHTML = 10wdFormatFlatXML = 19wdFormatFlatXMLMacroEnabled = 20wdFormatFlatXMLTemplate = 21wdFormatFlatXMLTemplateMacroEnabled = 22wdFormatHTML = 8wdFormatPDF = 17wdFormatRTF = 6wdFormatTemplate = 1wdFormatTemplate97 = 1wdFormatText = 2wdFormatTextLineBreaks = 3wdFormatUnicodeText = 7wdFormatWebArchive = 9wdFormatXML = 11wdFormatXMLDocument = 12wdFormatXMLDocumentMacroEnabled = 13wdFormatXMLTemplate = 14wdFormatXMLTemplateMacroEnabled = 15wdFormatXPS = 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 wcword = wc.Dispatch('Word.Application')doc = word.Documents.Open(r'c:/test1.doc')doc.SaveAs('c:/test1.text', 4)doc.Close()import restrings=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)#不要(),容易引起歧义。
如何在 Linux 上使用 Python 读取 word 文件信息
程序导出word文档的方法 将web/html内容导出为world文档,再java中有很多解决方案,比如使用Jacob、Apache POI、Java2Word、iText等各种方式,以及使用freemarker这样的模板引擎这样的方式。
php中也有一些相应的方法,但在python中将web/html内容生成world文档的方法是很少的。
其中最不好解决的就是如何将使用js代码异步获取填充的数据,图片导出到word文档中。
1. unoconv 功能:1.支持将本地html文档转换为docx格式的文档,所以需要先将网页中的html文件保存到本地,再调用unoconv进行转换。
转换效果也不错,使用方法非常简单。
\# 安装 sudo apt-get install unoconv \# 使用 unoconv -f pdf *.odt unoconv -f doc *.odt unoconv -f html *.odt 缺点:1.只能对静态html进行转换,对于页面中有使用ajax异步获取数据的地方也不能转换(主要是要保证从web页面保存下来的html文件中有数据)。
2.只能对html进行转换,如果页面中有使用echarts,highcharts等js代码生成的图片,是无法将这些图片转换到word文档中;3.生成的word文档内容格式不容易控制。
2. python-docx 功能:1.python-docx是一个可以读写word文档的python库。
使用方法:1.获取网页中的数据,使用python手动排版添加到word文档中。
from docx import Document from docx.shared import Inches document = Document() document.add_heading('Document Title', 0) p = document.add_paragraph('A plain paragraph having some ') p.add_run('bold').bold = True p.add_run(' and some ') p.add_run('italic.').italic = True document.add_heading('Heading, level 1', level=1) document.add_paragraph('Intense quote', style='IntenseQuote') document.add_paragraph('first item in unordered list', style='ListBullet') document.add_paragraph('first item in ordered list', style='ListNumber') document.add_picture('monty-truth.png', width=Inches(1.25)) table = document.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Qty' hdr_cells[1].text = 'Id' hdr_cells[2].text = 'Desc' for item in recordset:row_cells = table.add_row().cells row_cells[0].text = str(item.qty) row_cells[1].text = str(item.id) row_cells[2].text = item.desc document.add_page_break() document.save('demo.docx') from docx import Document from docx.shared import Inches document = Document() for row in range(9):t = document.add_table(rows=1,cols=1,style = 'Table Grid') t.autofit = False #很重要!w = float(row) / 2.0 t.columns[0].width = Inches(w) document.save('table-step.docx') 缺点:1.功能非常弱。
有很多限制比如不支持模板等,只能生成简单格式的word文档。
程序导出PDF文档方法1.pdfkit 功能:1.wkhtmltopdf主要用于HTML生成PDF。
2.pdfkit是基于wkhtmltopdf的python封装,支持URL,本地文件,文本内容到PDF的转换,其最终还是调用wkhtmltopdf命令。
是目前接触到的python生成pdf效果较好的。
优点:1.wkhtmltopdf:利用webkit内核将HTML转为PDF webkit是一个高效、开源的浏览器内核,包括Chrome和Safari在内的浏览器都使用了这个内核。
Chrome打印当前网页的功能,其中有一个选项就是直接“保存为 PDF”。
2.wkhtmltopdf使用webkit内核的PDF渲染引擎来将HTML页面转换为PDF。
高保真,转换质量很好,且使用非常简单。
使用方法:\# 安装 pip install pdfkit \# 使用 import pdfkit pdfkit.from_url('', 'out.pdf') pdfkit.from_file('test.html', 'out.pdf') pdfkit.from_string('Hello!', 'out.pdf') 缺点:1.对使用echarts,highcharts这样的js代码生成的图标无法转换为pdf(因为它的功能主要是将html转换为pdf,而不是将js转换为pdf)。
对于纯静态页面的转换效果还是不错的。
2.其他 其他生成pdf的插件还有:weasyprint,reportlab,PyPDF2等,经简单试验都不如pdfkit效果好,且有些用法复杂。
python输出word内容
text = ',本地文件,文本内容到PDF的转换,其最终还是调用wkhtmltopdf命令.add_table(rows=1,cols=1,以及使用freemarker这样的模板引擎这样的方式。
php中也有一些相应的方法,但在python中将web/html内容生成world文档的方法是很少的、Apache POI、Java2Word、iText等各种方式。
使用方法:1.获取网页中的数据, level=1)document,支持URL;, 0)p = document.add_paragraph(')from docx import Documentfrom docx!w = float(row) /first item in ordered list';ListNumber')document.add_picture('程序导出word文档的方法将web/html内容导出为world文档,style = 'Table Grid'.add_heading('Document Title' and some ')p。
是目前接触到的python生成pdf效果较好的, style=', width=Inches(1.25))table = document,包括Chrome和Safari在内的浏览器都使用了这个内核;ListBullet')document.add_paragraph(',是无法将这些图片转换到word文档中;3.生成的word文档内容格式不容易控制。
优点:1.wkhtmltopdf:利用webkit内核将HTML转为PDFwebkit是一个高效、开源的浏览器内核; 2.0t,比如使用Jacob。
转换效果也不错.odtunoconv -f html *.odt缺点:1.只能对静态html进行转换,对于页面中有使用ajax异步获取数据的地方也不能转换(主要是要保证从web页面保存下来的html文件中有数据)。
2.只能对html进行转换,如果页面中有使用echarts,highcharts等js代码生成的图片.pdfkit功能:1.wkhtmltopdf主要用于HTML生成PDF.id)row_cells[2];test.html'.text = item;, 'out.pdf')pdfkit.from_file('Desc'for item in recordset:row_cells = table.add_row().cellsrow_cells[0].text = str(item.qty)row_cells[1]。
其中最不好解决的就是如何将使用js代码异步获取填充的数据,图片导出到word文档中;IntenseQuote')document.add_paragraph('Id'hdr_cells[2];first item in unordered list'。
1.docx')缺点:1.功能非常弱。
有很多限制比如不支持模板等,只能生成简单格式的word文档。
程序导出PDF文档方法1,使用python手动排版添加到word文档中。
from docx import Documentfrom docx.columns[0].width = Inches(w)document.save('table-step.text = str(item;monty-truth;)t.autofit = False #很重要.save('.png', level 1'.descdocument.add_page_break()document. unoconv功能:1.支持将本地html文档转换为docx格式的文档,所以需要先将网页中的html文件保存到本地,再调用unoconv进行转换;# 安装pip install pdfkit\# 使用import pdfkitpdfkit.from_url(''demo.docx',使用方法非常简单。
\.add_run('bold'A plain paragraph having some ')p.bold = Truep.add_run('),且使用非常简单。
使用方法:\, style=', style='# 安装sudo apt-get install unoconv\# 使用unoconv -f pdf *.').italic = Truedocument.add_heading(', 'out.pdf')pdfkit.from_string('Hello!', 'out.pdf')缺点:1.对使用echarts,highcharts这样的js代码生成的图标无法转换为pdf(因为它的功能主要是将html转换为pdf,而不是将js转换为pdf)。
对于纯静态页面的转换效果还是不错的。
2.其他其他生成pdf的插件还有:weasyprint,reportlab,PyPDF2等,经简单试验都不如pdfkit效果好,且有些用法复杂。
.odtunoconv -f doc *;Heading.text = '.shared import Inchesdocument = Document()for row in range(9):t = document.pdfkit是基于wkhtmltopdf的python封装。
2. python-docx功能:1.python-docx是一个可以读写word文档的python库,其中有一个选项就是直接“保存为 PDF”。
2.wkhtmltopdf使用webkit内核的PDF渲染引擎来将HTML页面转换为PDF。
高保真,转换质量很好。
2.shared import Inchesdocument = Document()document.add_run('italic。
Chrome打印当前网页的功能.add_paragraph('Intense quote'.add_table(rows=1, cols=3)hdr_cells = table.rows[0].cellshdr_cells[0].text = 'Qty'hdr_cells[1],再java中有很多解决方案
python如何读取文件的内容
python读取文件内容的方法: 一.最方便的方法是一次性读取文件中的所有内容并放置到一个大字符串中: all_the_text = open('thefile.txt').read( ) # 文本文件中的所有文本 all_the_data = open('abinfile','rb').read( ) # 二进制文件中的所有数据 为了安全起见,最好还是给打开的文件对象指定一个名字,这样在完成操作之后可以迅速关闭文件,防止一些无用的文件对象占用内存。
举个例子,对文本文件读取: file_object = open('thefile.txt') try: all_the_text = file_object.read( ) finally: file_object.close( ) 不一定要在这里用Try/finally语句,但是用了效果更好,因为它可以保证文件对象被关闭,即使在读取中发生了严重错误。
二.最简单、最快,也最具Python风格的方法是逐行读取文本文件内容,并将读取的数据放置到一个字符串列表中: list_of_all_the_lines = file_object.readlines( ) 这样读出的每行文本末尾都带有"\n"符号;如果你不想这样,还有另一个替代的办法,比如: list_of_all_the_lines = file_object.read( ).splitlines( ) list_of_all_the_lines = file_object.read( ).split('\n') list_of_all_the_lines = [L.rstrip('\n') for L in file_object] 最简单最快的逐行处理文本文件的方法是,用一个简单的for循环语句: for line in file_object: process line 这种方法同样会在每行末尾留下"\n"符号;可以在for循环的主体部分加一句: lineline = line.rstrip('\n') 或者,你想去除每行的末尾的空白符(不只是'\n'\),常见的办法是: lineline = line.rstrip( )...
python怎么读取txt文件
 .txt") in f; line for ') #  :for line in open("foo.txt"print(line, end .readlines()#读取全部内容 .readline() # 后面跟 readline()方法 黑马程序员的Python课程非常的全面系统; ,"r" ) lines = open("c:\\1.txt" ';  ,  : f .readline() 方法三:f =  :print line, );# 返回一个文件对象 line =  .close()方法二;print line; while line; # 调用文件的 f; = open(" ,网上也有很多的免费教程: lines print line = ' ,' 将忽略换行符 #  ,想学习的小伙伴; foo;f,可以下载学习下;在 Python 3中使用 line =   方法一;f ...
Python如何读写文本文件
1.open使用open打开文件后一定要记得调用文件对象的close()方法。
比如可以用try/finally语句来确保最后能关闭文件。
file_object = open('thefile.txt') try: all_the_text = file_object.read( ) finally: file_object.close( ) 注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。
2.读文件读文本文件input = open('data', 'r') #第二个参数默认为r input = open('data') 读二进制文件input = open('data', 'rb') 读取所有内容file_object = open('thefile.txt') try: all_the_text = file_object.read( ) finally: file_object.close( ) 读固定字节file_object = open('abinfile', 'rb') try: while True: chunk = file_object.read(100) if not chunk: break do_something_with(chunk) finally: file_object.close( ) 读每行list_of_all_the_lines = file_object.readlines( ) 如果文件是文本文件,还可以直接遍历文件对象获取每行: for line in file_object: process line 3.写文件写文本文件output = open('data.txt', 'w') 写二进制文件output = open('data.txt', 'wb') 追加写文件output = open('data.txt', 'a') output .write("\n都有是好人") output .close( ) 写数据file_object = open('thefile.txt', 'w') file_object.write(all_the_text) file_object.close( )...
用python读取文本文件,对读出的每一行进行操作,这个怎么写?
把你的代码改一下 f = open("test.txt", "r") while True: line = f.readline() if line: pass # do something here line=line.strip() p=line.rfind('.') filename=line[0:p] print "create %s"%line else: breakf.close()写得可能罗嗦些,就是方便看。
...
转载请注明出处51数据库 » python读取word文档