office_parser.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import os, sys
  2. from io import BytesIO
  3. from markitdown import MarkItDown
  4. sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  5. from parser.document_parser import DocumentParser
  6. from logger.logging import setup_logging
  7. logger = setup_logging()
  8. class OfficeParser(DocumentParser):
  9. """Office文档解析器,使用markitdown"""
  10. def __init__(self):
  11. """初始化markitdown实例"""
  12. self.markitdown = MarkItDown(enable_plugins=False)
  13. def parse(self, data: bytes) -> str:
  14. """解析Office文档"""
  15. try:
  16. # 使用BytesIO创建文件类对象
  17. file_stream = BytesIO(data)
  18. # 使用markitdown的convert_stream方法解析
  19. result = self.markitdown.convert_stream(file_stream)
  20. if result and hasattr(result, 'text_content'):
  21. return result.text_content.strip()
  22. else:
  23. logger.error("markitdown解析结果为空或格式异常")
  24. return ""
  25. except Exception as e:
  26. logger.error(f"Office文档解析失败: {e}")
  27. return ""
  28. def supports(self, content_type: str) -> bool:
  29. """检查是否支持Office文档格式"""
  30. supported_types = [
  31. # Word文档
  32. 'application/msword', # .doc
  33. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', # .docx
  34. # Excel文档
  35. 'application/vnd.ms-excel', # .xls
  36. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', # .xlsx
  37. # PowerPoint文档
  38. 'application/vnd.ms-powerpoint', # .ppt
  39. 'application/vnd.openxmlformats-officedocument.presentationml.presentation', # .pptx
  40. # PDF (markitdown也支持PDF)
  41. 'application/pdf',
  42. ]
  43. return content_type.lower() in [t.lower() for t in supported_types]
  44. if __name__ == "__main__":
  45. parser = OfficeParser()
  46. with open("../data/msdoc3.docx", "rb") as f:
  47. data = f.read()
  48. result = parser.parse(data)
  49. print(result[:2000])