开发者社区> 问答> 正文

在python中读取Word文件

Python:3.7,平台:Win 10 64位

我想从MS Word文件中提取表格。我正在尝试使用以下代码在python中读取文件:

import win32com.client as win32


def parseWordFile(SigLexiconFilePath):
  print('parsing Word File')
  SigLexiconFilePath = "r\'" + SigLexiconFilePath
  commands = []
  word = win32.Dispatch("Word.Application")
  word.Visible = 0
  doc = word.Documents.Open(SigLexiconFilePath)

  table = doc.Tables(1)

代码似乎很明显,但是没有用。我正在获取doc变量,因为None它导致以下错误。

Exception has occurred: AttributeError
'NoneType' object has no attribute 'Tables

我在这里做错了什么?

PS:我发现doc = word.ActiveDocument如果MS Word程序中已打开文件,则添加行会打开该文件。但是我想打开单词文档,即使它还没有打开。

展开
收起
Puppet 2019-12-09 17:50:35 676 0
1 条回答
写回答
取消 提交回答
  • 感谢您指出文件路径中的错误。我试图以错误的方式将Windows的正斜杠路径转换为反斜杠路径。下面的代码修复了我的文件路径问题。

     
    
    import win32com.client as win32
    from pathlib import Path
    
    def parseWordFile(SigLexiconFilePath):
      print('parsing Word File')
      SigLexiconFilePath = Path(SigLexiconFilePath)
    
      commands = []
      word = win32.Dispatch("Word.Application")
      word.Visible = 0
      doc = word.Documents.Open(SigLexiconFilePath._str)
    
      table = doc.Tables(1)
    
    2019-12-09 17:51:34
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载