parsedocx.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. #-*-coding:utf-8 -*-
  2. import re,os
  3. import json,uuid
  4. from bs4 import BeautifulSoup
  5. from win32com.client import Dispatch
  6. import pythoncom
  7. from upload_to_oss import TedOSS
  8. import threading
  9. import shutil
  10. #from win32com.client.dynamic import Dispatch, ERRORS_BAD_CONTEXT
  11. class DocxConverter(object):
  12. """
  13. """
  14. def __init__(self,docpath="test4.docx"):
  15. """
  16. """
  17. self.docpath = docpath
  18. self.oss = TedOSS()
  19. def upload_imgfiles(self,uuidhtml):
  20. """
  21. """
  22. imgroot = os.path.join(os.path.dirname(self.docpath))
  23. imgdir = os.path.join(imgroot,uuidhtml+".files")
  24. if os.path.exists(imgdir):
  25. for file in os.listdir(imgdir):
  26. imgfile = os.path.join(imgdir,file)
  27. ossfile = uuidhtml+".files/"+file
  28. self.oss.upload_from_local(imgfile,ossfile)
  29. #shutil.rmtree(imgdir)
  30. pythoncom.CoUninitialize()
  31. def docx2html(self):
  32. """
  33. """
  34. pythoncom.CoInitialize()
  35. self.word = Dispatch("Word.Application")
  36. self.word.Visible = 0
  37. self.doc = self.word.Documents.Open(self.docpath)
  38. self.uuidhtml = str(uuid.uuid4())
  39. #html = os.path.join(os.path.dirname(self.docpath),self.uuidhtml+".html")
  40. html = os.path.join(os.path.dirname(self.docpath),self.uuidhtml+".html")
  41. self.doc.SaveAs(html,10)
  42. #pdffile = os.path.join(os.path.dirname(self.docpath),self.uuidhtml+".pdf")
  43. #self.doc.SaveAs(pdffile,17)
  44. #AvDoc = Dispatch("AcroExch.AVDoc")
  45. #try:
  46. # if AvDoc.Open(pdffile,""):
  47. # pdDoc = AvDoc.GetPDDoc()
  48. # jsObject = pdDoc.GetJSObject()
  49. # jsObject.SaveAs(html,"com.adobe.acrobat.html")
  50. #except Exception as e:
  51. # import traceback
  52. # traceback.print_exc()
  53. # AvDoc.close(True)
  54. #finally:
  55. # AvDoc.Close(True)
  56. self.doc.Close()
  57. self.word.Quit()
  58. os.remove(self.docpath)
  59. task = threading.Thread(target=self.upload_imgfiles,args=(self.uuidhtml,))
  60. task.start()
  61. return html
  62. class QuestionsParser(object):
  63. """试题解析
  64. """
  65. def __init__(self,name="test4.html"):
  66. self.html = open(name,"r").read()
  67. self.soup = BeautifulSoup(self.html,"html.parser")
  68. def get_paragraphs(self):
  69. """
  70. """
  71. wordsection = self.soup.find("div",class_="WordSection1")
  72. #print wordsection
  73. pars = wordsection.find_all("p")
  74. return pars
  75. def parse_questions(self):
  76. """提取试题
  77. """
  78. que_type_dct = {}
  79. paragraphs = self.get_paragraphs()
  80. for i,p in enumerate(paragraphs):
  81. print p.text
  82. if u"【题型】" in p.text:
  83. que_type_dct["type"] = p.text.split("、")[-1]
  84. def parse_questions(self):
  85. """提取试题
  86. """
  87. data = []
  88. tmp_val = {}
  89. tx_name = ""
  90. key = ""
  91. paragraphs = self.get_paragraphs()
  92. for i,p in enumerate(paragraphs):
  93. if u"【题型】" in p.text:
  94. tx_name = p.text
  95. if u"【题干】" in p.text:
  96. key = "tg"
  97. tmp_val["tx"] = tx_name
  98. if tmp_val.get("tg"):
  99. data.append(tmp_val)
  100. tmp_val = {"tg":"","tx":"","zsd":"","nd":"","da":"","jx":""}
  101. if u"【知识点】" in p.text:
  102. key = "zsd"
  103. if u"【难度】" in p.text:
  104. key = "nd"
  105. if u"【答案】" in p.text:
  106. key = "da"
  107. if u"【解析】" in p.text:
  108. key = "jx"
  109. if key != "":
  110. if "<img" in p.__str__():
  111. content = p.__str__()
  112. host = "http://scxjcclub.oss-cn-beijing.aliyuncs.com/say365/"
  113. src = re.search('src=".*\.files.*[\.jpg\.png]"',content).group().split("=")[-1].replace('"','')
  114. content = re.sub('src=".*\.files.*[\.jpg\.png]"','src="'+host+src+'"',content)
  115. tmp_val[key] += content
  116. else:
  117. tmp_val[key] += p.__str__()
  118. data.append(tmp_val)
  119. return data
  120. def get_questions(self):
  121. """
  122. """
  123. questions = self.parse_questions()
  124. for que in questions:
  125. que["tx"] = que["tx"].split(u"、")[-1]
  126. #que["tg"] = que["tg"].replace(u"【题干】","")
  127. #que["zsd"] = que["zsd"].replace(u"【知识点】","")
  128. #que["da"] = que["da"].replace(u"【答案】","")
  129. #que["jx"] = que["jx"].replace(u"【解析】","")
  130. que["qno"] = self.get_qno(que["tg"])
  131. return questions
  132. def get_qno(self,tg):
  133. """提取题号
  134. """
  135. tgsoup = BeautifulSoup(tg,"html.parser")
  136. tgtext = tgsoup.text
  137. qno = re.search(r"\d+",tgtext.split(u"、")[0]).group()
  138. return qno
  139. #docxconverter = DocxConverter()
  140. #questionparser = QuestionsParser()
  141. if __name__ == "__main__":
  142. #ques = questionparser.get_questions()
  143. #with open("t.json","w+") as f:
  144. # f.write(json.dumps(ques))
  145. #docxconverter.docx2html()
  146. pass