【问题标题】:Extracting Highlighted Words from Word Document (.docx) in Python在 Python 中从 Word 文档 (.docx) 中提取突出显示的单词
【发布时间】:2012-03-05 06:48:40
【问题描述】:

我正在处理一堆 word 文档,其中有突出显示的文本(单词)(使用颜色代码,例如黄色、蓝色、灰色),现在我想提取与每种颜色相关的突出显示的单词。我正在用 Python 编程。这是我目前所做的:

[python-docx][1]打开word文档,然后找到包含文档中标记(单词)的<w:r>标签。我使用了以下代码:

#!/usr/bin/env python2.6
# -*- coding: ascii -*-
from docx import *
document = opendocx('test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
  print word

现在我被困在检查每个单词是否具有<w:highlight> 标签并从中提取颜色代码以及它是否与<w:t> 标签内的黄色打印文本匹配的部分。如果有人能指出我从解析的文件中提取单词,我将不胜感激。

【问题讨论】:

    标签: python xml ms-word docx


    【解决方案1】:

    我以前从未使用过python-docx,但帮助我的是我在网上找到了一个关于突出显示的文本的 XML 结构看起来如何的 sn-p:

     <w:r>
        <w:rPr>
          <w:highlight w:val="yellow"/>
        </w:rPr>
        <w:t>text that is highlighted</w:t>
      </w:r>
    

    从那里,想出这个相对简单:

    from docx import *
    document = opendocx(r'test.docx')
    words = document.xpath('//w:r', namespaces=document.nsmap)
    
    WPML_URI = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
    tag_rPr = WPML_URI + 'rPr'
    tag_highlight = WPML_URI + 'highlight'
    tag_val = WPML_URI + 'val'
    
    for word in words:
        for rPr in word.findall(tag_rPr):
            if rPr.find(tag_highlight).attrib[tag_val] == 'yellow':
                print word.find(tag_t).text
    

    【讨论】:

    • 我做了一些小改动(缺少 tag_t 的声明和将 ascii 处理为 utf8 字符)修改后的代码可在gist.github.com/1982168 再次感谢@BioGeek!
    • 不客气。这是一个很酷的问题,我也学到了一些新东西。来自生物信息学家的问候!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    相关资源
    最近更新 更多