【问题标题】:Reading .doc file in Python using antiword in Windows (also .docx)在 Windows 中使用 antiword 读取 Python 中的 .doc 文件(也是 .docx)
【发布时间】:2018-08-07 12:49:22
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • doc 是一种过时的二进制格式。 docx 是一个包含 XML 文档的 zip 文件。您不能像阅读文本文件一样阅读它们中的任何一个
  • @PanagiotisKanavos 我必须使用 ML 根据文件内容执行文本分类任务。我有 .pdf .doc .docx 和 .txt 扩展名的文件。我这样做是为了从文件中获取文本内容,我错了吗?如果是这样,那么如果我无法从文件中读取文本,我该如何对文本进行分类。请澄清。

标签: python docx doc


【解决方案1】:

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

  • here下载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 文件的好方法。

希望对你有帮助,谢谢。

【讨论】:

  • 这里使用subprocess.check_output 并从antiword 中获取输出似乎比将其保存为docx 更简单。从我的使用来看,antiword 似乎无法将 doc 文件转换为 docx。你有什么不同的发现吗?
  • 子进程模块允许您生成新进程,连接到它们的输入/输出/错误管道,并获取它们的返回码。该模块旨在替换几个较旧的模块和功能,例如 os.system。在我的情况下,必须转换为 .docx 文件,因为我没有找到任何直接读取它们的方法。
  • 这适用于 64 位窗口,因此它必须是 64 位版本的 antiword。但它没有从官方网站链接。
【解决方案2】:

Mithilesh 的例子很好,但是一旦你安装了antiword,直接使用textract 会更简单。下载antiword,解压antiword文件夹到C:\。然后将 antiword 文件夹添加到您的 PATH 环境变量中。 (instructions for adding to PATH here)。打开一个新的终端或命令控制台以重新加载您的 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'))。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    相关资源
    最近更新 更多