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.pswp.cn/news/395344.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395344.shtml
英文地址,請注明出處:http://en.pswp.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;以及如何處理不同的區域、時區、…