用Python脚本解析.doc(Word)文件(Unix)

3 投票
2 回答
15092 浏览
提问于 2025-04-17 14:03

可能是重复的问题:
在Python中从MS Word文件提取文本

我想用Python写个脚本来解析一个.doc文件(也就是Word文档),目的是为了用某个表达式进行搜索。这个脚本是在Unix系统上运行的。

有没有人能帮帮我?

2 个回答

4

你可以使用 PyUno

这是一个示例:

# HelloWorld python script for the scripting framework

def HelloWorldPython( ):
    """Prints the string 'Hello World(in Python)' into the current document"""
#get the doc from the scripting context which is made available to all scripts
    model = XSCRIPTCONTEXT.getDocument()
#get the XText interface
    text = model.Text
#create an XTextRange at the end of the document
    tRange = text.End
#and set the string
    tRange.String = "Hello World (in Python)"
    return None

还有其他的 PyUNO 示例

3

你可以看看这个项目:python-docx。下载这个库后,你可以在命令行中运行 python example-extracttext.py docfile.docx textfile.txt | grep some-expression。当然,如果需要的话,你也可以在Python代码中进行更复杂的搜索。

不过,python-docx有个缺点,就是它目前只支持2007和2008版的微软Word。如果这对你很重要,我推荐你试试antiword,它支持微软Word的版本包括2、6、7、97、2000、2002和2003。其实我一直在我的vimrc中使用它,这样我就能在VIM编辑器中查看微软Word文件。虽然它不是一个Python脚本,但可以很方便地从Python中调用。

撰写回答