2013-01-31 77 views
2

我有几个表的文档文件。每张桌子都有两种颜色,黑色和红色。如何使用win32com从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 

您是否知道其他更好的方法来实现这一目标?

谢谢。

+0

'的xrange(N)'是'比范围更有效(0,N)' – eLRuLL

回答

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() 
+0

非常感谢你。我使用的是win32com,因为我需要使用.doc和.docx文档。我会看看你指出的图书馆。 – santi

相关问题