怎么把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文档中。
python怎样读取文本文件里的中文
#在Windows 环境下
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import re
fin = open('in.txt', 'r') #以读的方式打开输入文件
for eachLine in fin: #按行读入文件内容
line = eachLine.strip().decode('gbk', 'utf-8') #处理前进行相关的处理,包括转换成Unicode等
print line #打印原始字符
p2 = re.compile(ur'[^\u4e00-\u9fa5]') #中文的编码范围是:\u4e00到\u9fa5
zh = "".join(p2.split(line)).strip()
#zh = ",".join(zh.split())
print zh ##打印中文字符
用python编码提取包含指定中文词组的每行文本,并返回每行文本前面
python3 #============= word_list = ["物流","送货"]file_name = "xxx.txt" #要处理的txt文件名s = 0line_list = []with open(file_name,'r') as tp: for line in tp: for word in word_list: if word in line: line_list.append(line) s += int(line[0]) break print(s)for line in line_list: print(line.strip()) input()#============= 没有错误处理。
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数据库 » python获取word中文字符串