【问题标题】:How can I get the text by color from a word document with win32com?如何使用 win32com 从 word 文档中按颜色获取文本?
【发布时间】:2013-01-31 23:29:32
【问题描述】:

我有一个包含多个表格的 word 文档。每张桌子有两种颜色,黑色和红色。

我想通过颜色从 word 文档表格中的单元格中获取文本。我找到了一种方法,但我认为它的效率很低。

以下代码从单词表单元格中获取文本,并使用其颜色打印每个单词。

import os, sys
import win32com.client, re

path = os.path.join(os.getcwd(),"../files/tests2.docx")
word = win32com.client.Dispatch("Word.Application")
word.Visible = 1
doc=word.Documents.Open(path)

for table in doc.Tables:
    f = 2
    c = 2
    wc = table.Cell(f,c).Range.Words.Count
    for i in range(1,wc):
        print table.Cell(f,c).Range.Words(i), table.Cell(f,c).Range.Words(i).Font.Color

您知道实现此目的的任何其他(更好)方法吗?

谢谢。

【问题讨论】:

  • xrange(n)range(0,n) 效率更高

标签: python ms-word ms-office win32com


【解决方案1】:

这是一种使用 python-docx 从 Word 文档中提取突出显示的单词的方法:

#!usr/bin/python
# -*- coding: utf-8 -*-
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'
tag_t = WPML_URI + 't'
for word in words:
    for rPr in word.findall(tag_rPr):
        high=rPr.findall(tag_highlight)
        for hi in high:
            if hi.attrib[tag_val] == 'yellow':
                print word.find(tag_t).text.encode('utf-8').lower()

【讨论】:

  • 非常感谢。我正在使用 win32com,因为我需要同时处理 .doc 和 .docx 文档。我去看看你指出的图书馆。
猜你喜欢
  • 2019-02-05
  • 1970-01-01
  • 1970-01-01
  • 2011-07-24
  • 2015-03-19
  • 1970-01-01
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
相关资源
最近更新 更多