繁体   English   中英

在 Windows 中使用 antiword 读取 Python 中的 .doc 文件(也是 .docx)

[英]Reading .doc file in Python using antiword in Windows (also .docx)

我尝试阅读.doc文件,例如 -

with open('file.doc', errors='ignore') as f:
    text = f.read()

它确实读取了那个文件,但是有大量垃圾,我无法删除那个垃圾,因为我不知道它从哪里开始和结束。

我还尝试安装textract模块,它说它可以从任何文件格式读取,但是在 Windows 中下载它时存在许多依赖性问题。

所以我交替使用antiword命令行实用程序执行此操作,我的答案如下。

您可以使用antiword命令行实用程序来执行此操作,我知道你们中的大多数人都会尝试过,但我仍然想分享。

  • antiword文件夹解压缩到C:\并将路径C:\antiword添加到PATH环境变量中。

这是一个如何使用它的示例,处理 docx 和 doc 文件:

import os, docx2txt
def get_doc_text(filepath, file):
    if file.endswith('.docx'):
       text = docx2txt.process(file)
       return text
    elif file.endswith('.doc'):
       # converting .doc to .docx
       doc_file = filepath + file
       docx_file = filepath + file + 'x'
       if not os.path.exists(docx_file):
          os.system('antiword ' + doc_file + ' > ' + docx_file)
          with open(docx_file) as f:
             text = f.read()
          os.remove(docx_file) #docx_file was just to read, so deleting
       else:
          # already a file with same name as doc exists having docx extension, 
          # which means it is a different file, so we cant read it
          print('Info : file with same name of doc exists having docx extension, so we cant read it')
          text = ''
       return text

现在调用这个函数:

filepath = "D:\\input\\"
files = os.listdir(filepath)
for file in files:
    text = get_doc_text(filepath, file)
    print(text)

这可能是在Windows上用Python读取.doc文件的好方法。

希望对您有所帮助,谢谢。

Mithilesh 的示例很好,但是一旦安装了 antiword,直接使用textract会更简单。 下载antiword ,并将 antiword 文件夹解压缩到C:\ 然后将 antiword 文件夹添加到您的PATH环境变量中。 此处添加到 PATH 的说明)。 打开一个新的终端或命令控制台以重新加载您的PATH环境变量。 使用pip install textract

然后你可以像这样使用textract (对 .doc 文件使用antiword ):

import textract
text = textract.process('filename.doc')
text.decode('utf-8')  # converts from bytestring to string

如果您遇到错误,请尝试从终端/控制台运行命令antiword以确保其正常工作。 还要确保 .doc 文件的文件路径正确(例如使用os.path.exists('filename.doc') )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM