python word
代码:
#coding=utf-8
__author__ = 'zhm'
from win32com import client as wc
import os
import time
import random
import MySQLdb
import re
def wordsToHtml(dir):
#批量把文件夹的word文档转换成html文件
#金山WPS调用,抢先版的用KWPS,正式版WPS
word = wc.Dispatch('KWPS.Application')
for path, subdirs, files in os.walk(dir):
for wordFile in files:
wordFullName = os.path.join(path, wordFile)
#print "word:" + wordFullName
doc = word.Documents.Open(wordFullName)
wordFile2 = unicode(wordFile, "gbk")
dotIndex = wordFile2.rfind(".")
if(dotIndex == -1):
print '********************ERROR: 未取得后缀名!'
fileSuffix = wordFile2[(dotIndex + 1) : ]
if(fileSuffix == "doc" or fileSuffix == "docx"):
fileName = wordFile2[ : dotIndex]
htmlName = fileName + ".html"
htmlFullName = os.path.join(unicode(path, "gbk"), htmlName)
# htmlFullName = unicode(path, "gbk") + "\\" + htmlName
print u'生成了html文件:' + htmlFullName
doc.SaveAs(htmlFullName, 8)
doc.Close()
word.Quit()
print ""
print "Finished!"
def html_add_to_db(dir):
#将转换成功的html文件批量插入数据库中。
conn = MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='root',
db='test',
charset='utf8'
)
cur = conn.cursor()
for path, subdirs, files in os.walk(dir):
for htmlFile in files:
htmlFullName = os.path.join(path, htmlFile)
title = os.path.splitext(htmlFile)[0]
targetDir = 'D:/files/htmls/'
#D:/files为web服务器配置的静态目录
sconds = time.time()
msconds = sconds * 1000
targetFile = os.path.join(targetDir, str(int(msconds))+str(random.randint(100, 10000)) +'.html')
htmlFile2 = unicode(htmlFile, "gbk")
dotIndex = htmlFile2.rfind(".")
if(dotIndex == -1):
print '********************ERROR: 未取得后缀名!'
fileSuffix = htmlFile2[(dotIndex + 1) : ]
if(fileSuffix == "htm" or fileSuffix == "html"):
if not os.path.exists(targetDir):
os.makedirs(targetDir)
htmlFullName = os.path.join(unicode(path, "gbk"), htmlFullName)
htFile = open(htmlFullName,'rb')
#获取网页内容
htmStrCotent = htFile.read()
#找出里面的图片
img=re.compile(r"""<img\s.*?\s?src\s*=\s*['|"]?([^\s'"]+).*?>""",re.I)
m = img.findall(htmStrCotent)
for tagContent in m:
imgSrc = unicode(tagContent, "gbk")
imgSrcFullName = os.path.join(path, imgSrc)
#上传图片
imgTarget = 'D:/files/images/whzx/'
img_sconds = time.time()
img_msconds = sconds * 1000
targetImgFile = os.path.join(imgTarget, str(int(img_msconds))+str(random.randint(100, 10000)) +'.png')
if not os.path.exists(imgTarget):
os.makedirs(imgTarget)
if not os.path.exists(targetImgFile) or(os.path.exists(targetImgFile) and (os.path.getsize(targetImgFile) != os.path.getsize(imgSrcFullName))):
tmpImgFile = open(imgSrcFullName,'rb')
tmpWriteImgFile = open(targetImgFile, "wb")
tmpWriteImgFile.write(tmpImgFile.read())
tmpImgFile.close()
tmpWriteImgFile.close()
htmStrCotent=htmStrCotent.replace(tagContent,targetImgFile.split(":")[1])
if not os.path.exists(targetFile) or(os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(htmlFullName))):
#用iframe包装转换好的html文件。
iframeHtml='''
<script type="text/javascript" language="javascript">
function iFrameHeight() {
var ifm= document.getElementById("iframepage");
var subWeb = document.frames ? document.frames["iframepage"].document:ifm.contentDocument;
if(ifm != null && subWeb != null) {
ifm.height = subWeb.body.scrollHeight;
}
}
</script>
<iframe src='''+targetFile.split(':')[1]+'''
marginheight="0" marginwidth="0" frameborder="0" scrolling="no" width="765" height=100% id="iframepage" name="iframepage" onLoad="iFrameHeight()" ></iframe>
'''
tmpTargetFile = open(targetFile, "wb")
tmpTargetFile.write(htmStrCotent)
tmpTargetFile.close()
htFile.close()
try:
# 执行
sql = "insert into common_article(title,content) values(%s,%s)"
param = (unicode(title, "gbk"),iframeHtml)
cur.execute(sql,param)
except:
print "Error: unable to insert data"
cur.close()
conn.commit()
# 关闭数据库连接
conn.close()
if __name__ == '__main__':
wordsToHtml('d:/word')
html_add_to_db('d:/word')
python word的更多相关文章
- python word操作深入
python 把word转html:上传页面<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" &q ...
- python word转pdf
原理 使用python win32 库 调用word底层vba,将word转成pdf 安装pywin32 pip install pywin32 python代码 from win32com.clie ...
- Python初识(一)
首先我有编程语言的基础,你也有就最好了,这样会很快认识Python. 当然由于本人见识和学识的局限性,请广大猿/媛们多多包涵与指正(希望多评论哦),共同进步嘛. ◆ 准备环境:到python官网下载p ...
- 3. Python 简介
3. Python 简介 下面的例子中,输入和输出分别由大于号和句号提示符 ( >>> 和 ... ) 标注:如果想重现这些例子,就要在解释器的提示符后,输入 (提示符后面的) 那些 ...
- [Notes] Learn Python2.7 From Python Tutorial
I have planed to learn Python for many times. I have started to learn Python for many times . Howeve ...
- Python入门一:基本数据类型
作为一个刚入门编程的大一狗,第一次写博客,希望能对自己学的知识进行巩固和提升,也希望记录自己成长的过程. 学习Python,一是因为暑假学的c++头疼,听说Python简单,那我就试试吧,二是因为Py ...
- Python 基础之基本数据类型
首先,Python中的变量不需要声明.每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建.在Python中,变量就是变量,它没有类型,我们所说的"类型"是变量所指的内存中对象 ...
- Python 面向对象(一) 基础
Python 中一切皆对象 什么是面向对象? 面向对象就是将一些事物的共有特征抽象成类,从类来创建实例. 类class 可以理解为模版 比如人类,都具有身高.体重.年龄.性别.籍贯...等属性,但属性 ...
- python数据类型(一)
1.数据类型 python中数有四种类型:整数.长整数.浮点数和复数. 整数, 如 1 长整数 是比较大的整数 浮点数 如 1.23.3E-2 复数 如 1 + 2j. 1.1 + 2.2j 2. 自 ...
随机推荐
- 【Swift 2.1】为 UIView 添加点击事件和点击效果
前言 UIView 不像 UIButton 加了点击事件就会有点击效果,体验要差不少,这里分别通过自定义和扩展来实现类似 UIButton 的效果. 声明 欢迎转载,但请保留文章原始出处:) 博客园: ...
- 关于Ruby常用语法案例累积
变量问题: 类变量和方法变量的区别是什么? 类变量:可以直接使用 方法变量:需要实例化后,才能使用该变量 案例一: class Person @@name = "Tom" @@na ...
- 错误解决:error while loading shared libraries: libcurl.so.4: cannot open shared object file: No such file or directory
执行以下代码,生成唯一的UID $fp = popen("/xxx/bin/tools/uuidgen system", "r");// $uid = frea ...
- ORA-12523: TNS: 监听程序无法找到适用于客户机连接的例程
今天使用PL/SQL Developer连接到一台新的测试服务器时,遇到ORA错误:ORA-12523: TNS: 监听程序无法找到适用于客户机连接的例程.对应的监听日志文件里面错误为TNS-1252 ...
- 烂泥:haproxy学习之https配置
本文由ilanniweb提供友情赞助,首发于烂泥行天下 想要获得更多的文章,可以关注我的微信ilanniweb. 在前一段时间,我写了几篇有关学习haproxy的文章.今天我们再来介绍下haproxy ...
- openstack 命令行管理 - 目录
原文http://blog.csdn.net/signmem/article/details/19513775 相关 openstack 命令行管理, 分下面部分进行介绍 openstack 命令行 ...
- mvn常用命令
1. mvn compile 编译源代码 2. mvn test-compile 编译测试代码 3. mvn test 运行测试 4. mvn package 打包,根据pom.xml打成war或ja ...
- [转]Python 字符串操作实现代码(截取/替换/查找/分割)
原文地址:http://www.jb51.net/article/38102.htm ps:好久没更新python代码了,这次用到了字符串,转来看看 Python 截取字符串使用 变量[头下标:尾下标 ...
- python Requests模块的简要介绍
Requests的安装: pip install Requests Requests的使用: import requests url = "http://www.mzitu.com" ...
- mongodb基本操作的学习
1.基本操作: 如何安装?创建存放数据的文件夹 robomongo: 图形化管理工具 create -->save -->connect 创建数据库:use Database_name 检 ...