繁体   English   中英

使用 python 读取 .doc 文件

[英]Read .doc file with python

我得到了一份工作申请测试,我的交易是阅读一些 .doc 文件。 有谁知道图书馆可以做到这一点? 我从原始的 python 代码开始:

f = open('test.doc', 'r')
f.read()

但这不会返回友好的字符串,我需要将其转换为 utf-8

编辑:我只想从此文件中获取文本

可以使用texttract库。 它同时处理“doc”和“docx”

import textract
text = textract.process("path/to/file.extension")

您甚至可以使用“antiword”(sudo apt-get install antiword),然后将 doc to first 转换为 docx,然后通读docx2txt

antiword filename.doc > filename.docx

最终,后端的 textract 使用的是 antiword。

您可以使用python-docx2txt库从 Microsoft Word 文档中读取文本。 它是对python-docx库的改进,因为它还可以从链接、页眉和页脚中提取文本。 它甚至可以提取图像。

您可以通过运行来安装它: pip install docx2txt

让我们在这里下载并阅读第一个 Microsoft 文档:

import docx2txt
my_text = docx2txt.process("test.docx")
print(my_text)

这是终端输出上述代码的屏幕截图:

在此处输入图片说明

编辑:

.doc文件工作。 我保留这个答案的唯一原因是似乎有人发现它对.docx文件有用。

我也试图这样做,我发现了很多关于阅读 .docx 的信息,但很少有关于 .doc 的信息; 无论如何,我设法使用以下内容阅读了文本:

import win32com.client

word = win32com.client.Dispatch("Word.Application")
word.visible = False
wb = word.Documents.Open("myfile.doc")
doc = word.ActiveDocument
print(doc.Range().Text)

Shivam Kotwalia 的回答非常有效。 但是,对象是作为字节类型导入的。 有时你可能需要它作为一个字符串来执行 REGEX 或类似的东西。

我推荐以下代码(Shivam Kotwalia 的回答中的两行):

import textract

text = textract.process("path/to/file.extension")
text = text.decode("utf-8") 

最后一行将对象文本转换为字符串

我同意 Shivam 的回答,除了 windows 不存在textract 而且,由于某种原因, antiword也无法读取“.doc”文件并给出错误:

'filename.doc' is not a word document. # This happens when the file wasn't generated via MS Office. Eg: Web-pages may be stored in .doc format offline.

所以,我有以下解决方法来提取文本:

from bs4 import BeautifulSoup as bs
soup = bs(open(filename).read())
[s.extract() for s in soup(['style', 'script'])]
tmpText = soup.get_text()
text = "".join("".join(tmpText.split('\t')).split('\n')).encode('utf-8').strip()
print text

此脚本适用于大多数类型的文件。 玩得开心!

先决条件:

安装 antiword : sudo apt-get install antiword

安装 docx : pip install docx

from subprocess import Popen, PIPE

from docx import opendocx, getdocumenttext
from cStringIO import StringIO
def document_to_text(filename, file_path):
    cmd = ['antiword', file_path]
    p = Popen(cmd, stdout=PIPE)
    stdout, stderr = p.communicate()
    return stdout.decode('ascii', 'ignore')

print document_to_text('your_file_name','your_file_path')

注意 – 新版本的 python-docx 删除了这个功能。 确保 pip install docx 而不是新的 python-docx

!pip 安装 python-docx

import docx

#Creating a word file object
doc = open("file.docx","rb")

#creating word reader object
document = docx.Document(doc)

我不得不做同样的事情来搜索大量的 *.doc 文件以获取特定数字并提出:

special_chars = {
    "b'\\t'": '\t',
    "b'\\r'": '\n',
    "b'\\x07'": '|',
    "b'\\xc4'": 'Ä',
    "b'\\xe4'": 'ä',
    "b'\\xdc'": 'Ü',
    "b'\\xfc'": 'ü',
    "b'\\xd6'": 'Ö',
    "b'\\xf6'": 'ö',
    "b'\\xdf'": 'ß',
    "b'\\xa7'": '§',
    "b'\\xb0'": '°',
    "b'\\x82'": '‚',
    "b'\\x84'": '„',
    "b'\\x91'": '‘',
    "b'\\x93'": '“',
    "b'\\x96'": '-',
    "b'\\xb4'": '´'
}


def get_string(path):
    string = ''
    with open(path, 'rb') as stream:
        stream.seek(2560) # Offset - text starts after byte 2560
        current_stream = stream.read(1)
        while not (str(current_stream) == "b'\\xfa'"):
            if str(current_stream) in special_chars.keys():
                string += special_chars[str(current_stream)]
            else:
                try:
                    char = current_stream.decode('UTF-8')
                    if char.isalnum():
                        string += char
                except UnicodeDecodeError:
                    string += ''
            current_stream = stream.read(1)
    return string

我不确定这个解决方案有多“干净”,但它适用于正则表达式。

我一直在寻找解决方案。 .doc文件资料不够,最后我把类型.doc .docx解决了这个问题

from win32com import client as wc
w = wc.Dispatch('Word.Application')
# Or use the following method to start a separate process:
# w = wc.DispatchEx('Word.Application')
doc=w.Documents.Open(os.path.abspath('test.doc'))
doc.SaveAs("test_docx.docx",16)

如果您正在寻找如何阅读 python 中的文档文件,则此代码将运行,首先安装所有相关包并查看结果。

如果文档文件:

    _file=requests.get(request.values['MediaUrl0'])

    doc_file_link=BytesIO(_file.content)

    file_path=os.getcwd()+'\+data.doc'

    E=open(file_path,'wb')
    E.write(doc_file_link.getbuffer())
    E.close()

    word = win32.gencache.EnsureDispatch('Word.Application',pythoncom.CoInitialize())
    doc = word.Documents.Open(file_path)
    doc.Activate()
    doc_data=doc.Range().Text
    print(doc_data)
    doc.Close(False)

    if os.path.exists(file_path):
       os.remove(file_path)

暂无
暂无

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

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