如何通过win32com从Word文档中获取按颜色的文本?
我有一个Word文档,里面有好几个表格。每个表格里有两种颜色,黑色和红色。
我想根据单元格的颜色来提取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
你知道有没有其他(更好的)方法可以做到这一点吗?
谢谢。
1 个回答
3
这里有一种方法可以从Word文档中提取高亮的单词,使用的是python-docx这个库:
#!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()