2013-01-31 97 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

相關問題