在Python中处理MS Word文件,可以使用Python Win32扩展,在Windows系统中使用。那在Linux操作系统下如何实现相同的功能?有没有相关的库可用?
使用 原生Python docx模块。以下是从doc中提取所有文本的方法:
document = docx.Document(filename)
docText = '\n\n'.join(
paragraph.text for paragraph in document.paragraphs
)
print(docText)
另外请查看Textract,可以提取表格等内容。
使用正则表达式解析XML会唤醒克苏鲁。 不要这样做!
from docx import *
吗?如果不是,那你是怎么获取 getdocumenttext
等内容的呢? - abcdimport docx; document = docx.Document('Hello world.docx')
。 - egpbosBenjamin的回答非常不错。我刚刚整理了一下...
import zipfile, re
docx = zipfile.ZipFile('/path/to/file/mydocument.docx')
content = docx.read('word/document.xml').decode('utf-8')
cleaned = re.sub('<(.|\n)*?>','',content)
print(cleaned)
- Jesvin Jose从xml.sax.saxutils导入unescape text = unescape(cleaned)
OpenOffice.org可以使用Python进行脚本编写:请参见此处。
由于OOo可以完美加载大多数MS Word文件,我认为那是您最好的选择。
import commands
exe = 'wvText ' + word_file + ' ' + output_txt_file
out = commands.getoutput(exe)
exe = 'cat ' + output_txt_file
out = commands.getoutput(exe)
就是这样。基本上,我们正在使用commands.getouput函数来运行一些shell脚本,即wvText(从Word文档中提取文本)和cat(读取文件输出)。之后,整个Word文档的所有文本都将在out变量中,可以随时使用。
希望这能帮助未来遇到类似问题的人们。
要读取Word 2007及更高版本文件,包括.docx文件,您可以使用python-docx软件包:
from docx import Document
document = Document('existing-document-file.docx')
document.save('new-file-name.docx')
若要读取Word 2003及以前版本的.doc文件,请调用子进程antiword。您需要先安装antiword:
sudo apt-get install antiword
import os
input_word_file = "input_file.doc"
output_text_file = "output_file.txt"
os.system('antiword %s > %s' % (input_word_file, output_text_file))
现在,这很丑陋而且相当hacky,但对于基本文本提取来说,它似乎对我有效。显然,在Qt程序中使用它,您必须为其生成一个进程,但我已经组合好了以下命令行:
unzip -p file.docx | grep '<w:t' | sed 's/<[^<]*>//g' | grep -v '^[[:space:]]*$'
所以:
unzip -p file.docx: -p == "将文件解压到标准输出"
grep '<w:t': 抓取包含“<w:t”(据我所知,<w:t>是Word 2007 XML元素,表示“文本”)的行
sed 's/<[^<]>//g'*: 删除标签内的所有内容
grep -v '^[[:space:]]$'*: 删除空行
可能有更有效的方法来完成这个操作,但在我测试过的一些文档上似乎可行。
据我所知,unzip、grep 和 sed 都有适用于 Windows 和任何 Unix 的版本,因此应该相当跨平台。尽管这是一种比较丑陋的 hack ;)
如果文档包含复杂的表格、文本框、嵌入式电子表格等,则可能无法按预期工作。开发良好的MS Word过滤器是一个非常困难的过程,因此请耐心等待我们努力使Word文档正确打开。如果您有一个无法加载的Word文档,请打开Bug并包含该文档,以便我们改进导入程序。
如果你的意图是仅使用Python模块而不调用子进程,你可以使用zipfile Python模块。
content = ""
# Load DocX into zipfile
docx = zipfile.ZipFile('/home/whateverdocument.docx')
# Unpack zipfile
unpacked = docx.infolist()
# Find the /word/document.xml file in the package and assign it to variable
for item in unpacked:
if item.orig_filename == 'word/document.xml':
content = docx.read(item.orig_filename)
else:
pass
您的内容字符串需要进行清理,其中一种方法是:
# Clean the content string from xml tags for better search
fullyclean = []
halfclean = content.split('<')
for item in halfclean:
if '>' in item:
bad_good = item.split('>')
if bad_good[-1] != '':
fullyclean.append(bad_good[-1])
else:
pass
else:
pass
# Assemble a new string with all pure content
content = " ".join(fullyclean)
- Jesvin Josefrom xml.sax.saxutils import unescape text = unescape(content)
stripped_content = re.compile(b'<.*?>').sub(b' ', content) # strip tags
你代码中有一件事我不明白,在前面的片段中为什么你没有在if块内部使用break? - Vikas Prasad