python word

 代码:

  1 #coding=utf-8
  2 __author__ = 'zhm'
  3 from win32com import client as wc
  4 import os
  5 import time
  6 import random
  7 import MySQLdb
  8 import re
  9 def wordsToHtml(dir):
 10 #批量把文件夹的word文档转换成html文件
 11  #金山WPS调用,抢先版的用KWPS,正式版WPS
 12  word = wc.Dispatch('KWPS.Application')
 13  for path, subdirs, files in os.walk(dir):
 14   for wordFile in files:
 15    wordFullName = os.path.join(path, wordFile)
 16    #print "word:" + wordFullName
 17    doc = word.Documents.Open(wordFullName)
 18    wordFile2 = unicode(wordFile, "gbk")
 19    dotIndex = wordFile2.rfind(".")
 20    if(dotIndex == -1):
 21     print '********************ERROR: 未取得后缀名!'
 22    fileSuffix = wordFile2[(dotIndex + 1) : ]
 23    if(fileSuffix == "doc" or fileSuffix == "docx"):
 24     fileName = wordFile2[ : dotIndex]
 25     htmlName = fileName + ".html"
 26     htmlFullName = os.path.join(unicode(path, "gbk"), htmlName)
 27     # htmlFullName = unicode(path, "gbk") + "\\" + htmlName
 28     print u'生成了html文件:' + htmlFullName
 29     doc.SaveAs(htmlFullName, 8)
 30     doc.Close()
 31  word.Quit()
 32  print ""
 33  print "Finished!"
 34 def html_add_to_db(dir):
 35 #将转换成功的html文件批量插入数据库中。
 36  conn = MySQLdb.connect(
 37   host='localhost',
 38   port=3306,
 39   user='root',
 40   passwd='root',
 41   db='test',
 42   charset='utf8'
 43   )
 44  cur = conn.cursor()
 45  for path, subdirs, files in os.walk(dir):
 46   for htmlFile in files:
 47    htmlFullName = os.path.join(path, htmlFile)
 48    title = os.path.splitext(htmlFile)[0]
 49    targetDir = 'D:/files/htmls/'
 50    #D:/files为web服务器配置的静态目录
 51    sconds = time.time()
 52    msconds = sconds * 1000
 53    targetFile = os.path.join(targetDir, str(int(msconds))+str(random.randint(100, 10000)) +'.html')
 54    htmlFile2 = unicode(htmlFile, "gbk")
 55    dotIndex = htmlFile2.rfind(".")
 56    if(dotIndex == -1):
 57     print '********************ERROR: 未取得后缀名!'
 58    fileSuffix = htmlFile2[(dotIndex + 1) : ]
 59    if(fileSuffix == "htm" or fileSuffix == "html"):
 60     if not os.path.exists(targetDir):
 61      os.makedirs(targetDir)
 62     htmlFullName = os.path.join(unicode(path, "gbk"), htmlFullName)
 63     htFile = open(htmlFullName,'rb')
 64     #获取网页内容
 65     htmStrCotent = htFile.read()
 66     #找出里面的图片
 67     img=re.compile(r"""<img\s.*?\s?src\s*=\s*['|"]?([^\s'"]+).*?>""",re.I)
 68     m = img.findall(htmStrCotent)
 69     for tagContent in m:
 70      imgSrc = unicode(tagContent, "gbk")
 71      imgSrcFullName = os.path.join(path, imgSrc)
 72      #上传图片
 73      imgTarget = 'D:/files/images/whzx/'
 74      img_sconds = time.time()
 75      img_msconds = sconds * 1000
 76      targetImgFile = os.path.join(imgTarget, str(int(img_msconds))+str(random.randint(100, 10000)) +'.png')
 77      if not os.path.exists(imgTarget):
 78       os.makedirs(imgTarget)
 79      if not os.path.exists(targetImgFile) or(os.path.exists(targetImgFile) and (os.path.getsize(targetImgFile) != os.path.getsize(imgSrcFullName))):
 80       tmpImgFile = open(imgSrcFullName,'rb')
 81       tmpWriteImgFile = open(targetImgFile, "wb")
 82       tmpWriteImgFile.write(tmpImgFile.read())
 83       tmpImgFile.close()
 84       tmpWriteImgFile.close()
 85       htmStrCotent=htmStrCotent.replace(tagContent,targetImgFile.split(":")[1])
 86     if not os.path.exists(targetFile) or(os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(htmlFullName))):
 87      #用iframe包装转换好的html文件。
 88      iframeHtml='''
 89      <script type="text/javascript" language="javascript">
 90       function iFrameHeight() {
 91        var ifm= document.getElementById("iframepage");
 92        var subWeb = document.frames ? document.frames["iframepage"].document:ifm.contentDocument;
 93        if(ifm != null && subWeb != null) {
 94         ifm.height = subWeb.body.scrollHeight;
 95        }
 96       }
 97      </script>
 98      <iframe src='''+targetFile.split(':')[1]+'''
 99       marginheight="0" marginwidth="0" frameborder="0" scrolling="no" width="765" height=100% id="iframepage" name="iframepage" onLoad="iFrameHeight()" ></iframe>
100      '''
101      tmpTargetFile = open(targetFile, "wb")
102      tmpTargetFile.write(htmStrCotent)
103      tmpTargetFile.close()
104      htFile.close()
105      try:
106       # 执行
107       sql = "insert into common_article(title,content) values(%s,%s)"
108       param = (unicode(title, "gbk"),iframeHtml)
109       cur.execute(sql,param)
110      except:
111       print "Error: unable to insert data"
112  cur.close()
113  conn.commit()
114  # 关闭数据库连接
115  conn.close()
116 if __name__ == '__main__':
117  wordsToHtml('d:/word')
118  html_add_to_db('d:/word')

 

转载于:https://www.cnblogs.com/kamil/p/5772903.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/395344.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

aws lambda_如何为AWS Lambda实施日志聚合

aws lambdaby Yan Cui崔燕 如何为AWS Lambda实施日志聚合 (How to implement log aggregation for AWS Lambda) During the execution of a Lambda function, whatever you write to stdout (for example, using console.log in Node.js) will be captured by Lambda and sent…

【Python3爬虫】为什么你的博客没人看呢?

我相信对于很多爱好和习惯写博客的人来说&#xff0c;如果自己的博客有很多人阅读和评论的话&#xff0c;自己会非常开心&#xff0c;但是你发现自己用心写的博客却没什么人看&#xff0c;多多少少会觉得有些伤心吧&#xff1f;我们今天就来看一下为什么你的博客没人看呢&#…

泰安高考2021成绩查询,泰安高考成绩查询入口2021

高考结束之后&#xff0c;为了方便大家进行高考成绩的查询&#xff0c;下面跟着出国留学网小编来一起看看“泰安高考成绩查询入口2021”&#xff0c;仅供参考&#xff0c;希望对大家有帮助。2021山东高考成绩查询时间及志愿填报时间根据山东2021年夏季高考须知&#xff0c;2021…

用GitHub Issue取代多说,是不是很厉害?

2019独角兽企业重金招聘Python工程师标准>>> 摘要: 别了&#xff0c;多说&#xff0c;拥抱Gitment。 2017年6月1日&#xff0c;多说正式下线&#xff0c;这多少让人感觉有些遗憾。在比较了多个博客评论系统&#xff0c;我最终选择了Gitment作为本站的博客评论系统&a…

mysql延时优化教程_Mysql优化之延迟索引和分页优化_MySQL

什么是延迟索引&#xff1f;使用索引查询出来数据&#xff0c;之后把查询结果和同一张表中数据进行连接查询&#xff0c;进而提高查询速度!分页是一个很常见功能&#xff0c;select ** from tableName limit ($page - 1 ) * $n ,$n通过一个存储过程插入10000条数据进行测试&…

【动态规划】Vijos P1313 金明的预算方案(NOIP2006提高组第二题)

题目链接&#xff1a; https://vijos.org/p/1313 题目大意&#xff1a; m(m<32000)金钱&#xff0c;n&#xff08;n<60&#xff09;个物品&#xff0c;花费vi&#xff0c;价值vi*ci,每个物品可能有不超过2个附件&#xff0c;附件没有附件。 题目思路&#xff1a; 【动态规…

计算机网络应用答题卡,2013-2014学年第2学期11级计算机网络技术毕业考试试卷

2013-2014学年第2学期11级《计算机网络技术》课程毕业考试试卷得分&#xff1a;一、单项选择题&#xff1a;(每题1分&#xff0c;共30分&#xff0c;答案必须写在后面的选择题答题卡内&#xff0c;否则不得分)1、计算机网络可以按网络的覆盖范围来划分&#xff0c;以下()不是按…

0622 - 如何坚守自己的价值观?

如果有人有着和自己迥异的价值观&#xff0c;且混得很好&#xff0c;且和自己是熟人&#xff0c;自己是不是要改变自己、向其学习&#xff1f; 比如&#xff0c;常说的「学习好的比学习差的打工」&#xff0c;那到底是要好好学习&#xff0c;还是提前混人脉、攒经验&#xff1f…

如何免费注册Coursera课程

One question I get asked all the time here at Class Central is: are Coursera courses really free?在班级中心&#xff0c;我一直被问到的一个问题是&#xff1a; Coursera课程真的免费吗&#xff1f; Coursera’s user interface is intentionally designed to push le…

三态门有一个信号控制端en_三态门verilog

双向口-三态门的电路IC专业技术文章2008-12-06 14:59:24阅读119评论0字号&#xff1a;大中小订阅1.TTL三态门电路工作原理:三态门电路的基本结构如下图所示&#xff1a;(1)图1给出了三态门的电路结构图及图形符号。其中控制端EN为低电平时,P点为高电平&#xff0c;二极管D截止&…

[树形dp] Jzoj P3914 人品问题

Description 网上出现了一种高科技产品——人品测试器。只要你把你的真实姓名输入进去&#xff0c;系统将自动输出你的人品指数。yzx不相信自己的人品为0。经过了许多研究后&#xff0c;yzx得出了一个更为科学的人品计算方法。这种方法的理论依据是一个非常重要的结论&#xff…

为什么那些每三年跳一次槽的人越跳越好? - 震撼

现在&#xff0c;人们已经放下了对跳槽的偏见。这是一件好事。之前。假设你每几年换一次工作&#xff0c;人们会认为你的简历上有 “污点”。面试官会认为你无法胜任一份工作。与同事相处不好。或者你对公司不忠诚&#xff0c;不能承担任务&#xff0c;等等。 这样的想法非常快…

2019 6月编程语言_六月开始提供435项免费在线编程和计算机科学课程

2019 6月编程语言Five years ago, universities like MIT and Stanford first opened up free online courses to the public. Today, more than 700 schools around the world have created thousands of free online courses.五年前&#xff0c;麻省理工学院和斯坦福大学等大…

使用html记笔记,开始学习HTML,并记下笔记

开始学习HTML,并记下笔记。外边距(不影响可见框大小&#xff0c;影像盒子位置)margin-top(上)right(右)bottom(下)left(左)“外边距也可以为一个负值&#xff0c;元素会反方向移动”margin还可以设置为auto&#xff0c;auto一般只设置给水平方向的margin.如果只指定&#xff0c…

矢量合成和分解的法则_专题14 运动的合成与分解

运动的合成与分解【基础回顾】 考点内容:运动的合成与分解 考纲解读: 1.掌握曲线运动的概念、特点及条件. 2.掌握运动的合成与分解法则&#xff0e; 考点一 物体做曲线运动的条件及轨迹分析 1&#xff0e;条件  (1)因为速度时刻在变&#xff0c;所以一定存在加速度&#xff1…

详解--单调队列 经典滑动窗口问题

单调队列&#xff0c;即单调的队列。使用频率不高&#xff0c;但在有些程序中会有非同寻常的作用。 动态规划单调队列的理解 做动态规划时常常会见到形如这样的转移方程&#xff1a;f[x] max or min{g(k) | b[x] < k < x} w[x](其中b[x]随x单调不降&#xff0c;即b[1]&…

Java Persistence with MyBatis 小结2

MyBatis 最关键的组成部分是 SqlSessionFactory&#xff0c;我们可以从中获取 SqlSession&#xff0c;并执行映射的 SQL 语句。SqlSessionFactory 对象可以通过基于 XML 的配置信息或者 Java API 创建。 1 mybatis环境&#xff0c;environments 配置默认的数据库环境 MyBatis 支…

《计算机应用基础》18春作业,【北语网院】18春《计算机应用基础》作业_2.pdf...

谋学网【北京语言大学】 18 春《计算机应用基础》作业 _2试卷总分 :100 得分 :100第 1 题, 操作系统是 ___ 的接口。A、用户与软件B、系统软件与应用软件C、主机与外设D、用户与计算机第 2 题, 计算机配置的内存的容量为 128MB或 128MB以上&#xff0c;其中的 128MB是指 __ 。A…

freeCodeCamp纳什维尔十月聚会回顾

by Seth Alexander塞斯亚历山大(Seth Alexander) 纳什维尔的美好时光&#xff1a;十月免费CodeCamp聚会的回顾 (Good times in Nashville: a recap of our October freeCodeCamp Meetup) On Saturday, October 7, we had our monthly freeCodeCamp Nashville meetup at Nashvi…

c#时分秒毫秒微妙_你真的清楚DateTime in C#吗?

DateTime&#xff0c;就是一个世界的大融合。日期和时间&#xff0c;在我们开发中非常重要。DateTime在C#中&#xff0c;专门用来表达和处理日期和时间。本文算是多年使用DateTime的一个总结&#xff0c;包括DateTime对象的整体应用&#xff0c;以及如何处理不同的区域、时区、…