Ita*_*mos 10 python python-2.7
我得到了求职申请的测试,我的交易是读了一些.doc文件.有谁知道图书馆这样做?我开始使用原始python代码:
f = open('test.doc', 'r')
f.read()
Run Code Online (Sandbox Code Playgroud)
但这不会返回我需要将其转换为utf-8的友好字符串
编辑:我只想从这个文件中获取文本
Shi*_*lia 22
可以使用textract库.它既包括"doc",也包括"docx"
import textract
text = textract.process("path/to/file.extension")
Run Code Online (Sandbox Code Playgroud)
您甚至可以使用'antiword'(sudo apt-get install antiword)然后将doc转换为docx,然后通过docx2txt进行读取.
antiword filename.doc > filename.docx
Run Code Online (Sandbox Code Playgroud)
最终,后端的textract正在使用antiword.
Bil*_*adj 11
您可以使用python-docx2txt库从Microsoft Word文档中读取文本.这是对python-docx库的改进,因为它还可以从链接,页眉和页脚中提取文本.它甚至可以提取图像.
你可以运行:安装它 pip install docx2txt
.
我们在这里下载并阅读第一篇Microsoft文档:
import docx2txt
my_text = docx2txt.process("test.docx")
print(my_text)
Run Code Online (Sandbox Code Playgroud)
以下是终端输出上面代码的截图:
编辑:
但这不是对工作的.doc文件.我保留这个答案的唯一原因是,似乎有人发现它对.docx文件很有用.
小智 10
Shivam Kotwalia 的回答非常有效。但是,对象是作为字节类型导入的。有时你可能需要它作为一个字符串来执行 REGEX 或类似的东西。
我推荐以下代码(Shivam Kotwalia 的回答中的两行):
import textract
text = textract.process("path/to/file.extension")
text = text.decode("utf-8")
Run Code Online (Sandbox Code Playgroud)
最后一行将对象文本转换为字符串。
我试图做到同样,我发现了很多阅读.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)
Run Code Online (Sandbox Code Playgroud)
我同意 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.
Run Code Online (Sandbox Code Playgroud)
所以,我有以下解决方法来提取文本:
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
Run Code Online (Sandbox Code Playgroud)
此脚本适用于大多数类型的文件。玩得开心!
先决条件:
\n\n安装反词:sudo apt-get install antiword
安装文档:pip install docx
from subprocess import Popen, PIPE\n\nfrom docx import opendocx, getdocumenttext\nfrom cStringIO import StringIO\ndef document_to_text(filename, file_path):\n cmd = ['antiword', file_path]\n p = Popen(cmd, stdout=PIPE)\n stdout, stderr = p.communicate()\n return stdout.decode('ascii', 'ignore')\n\nprint document_to_text('your_file_name','your_file_path')\n
Run Code Online (Sandbox Code Playgroud)\n\n注意 \xe2\x80\x93 新版本的 python-docx 删除了这个功能。确保 pip install docx 而不是新的 python-docx
\n 归档时间: |
|
查看次数: |
64189 次 |
最近记录: |