我正在尝试访问Word文档中的所有文本,然后对其进行修改。这是为了一个更广泛的项目。到目前为止,我已经能够访问大部分段落、表格等。现在我无法找到修改文本框内容的方法。
到目前为止,我正在使用 python docx 库来完成此任务。我还使用底层 lxml 包来处理图片和形状,我正在共享一个处理段落和底层图片的代码片段,作为示例,我将文件的所有内容更改为字符串 'a ' 并且该代码适用于大多数文本。如何访问文本框???
for paragraph in doc.paragraphs:
for run in paragraph.runs:
if run.text:
old_text = run.text
lst_of_words = old_text.split(' ')
n_w_l = []
for i in lst_of_words:
l = len(i)
n_w = ''
for j in range(l):
n_w += 'a'
n_w_l.append(n_w)
new_text = ' '.join(n_w_l)
# Replace each word with its corresponding 'a's
#for old_word, new_word in zip(lst_of_words, n_w_l):
# old_text = old_text.replace(old_word, new_word, 1)
run.text=run.text.replace(old_text,new_text)
print(new_text)
# Replace the text of the run
#run.text = old_text
elif run._r.getchildren()[0].tag.endswith('drawing'):
# If the run contains an image
drawing = run._r.getchildren()[0]
inline = drawing.getchildren()[0]
blip = inline.getchildren()[0]
img_bytes = blip._blob
width = inline.extent.cx
height = inline.extent.cy
new_run = paragraph.add_run()
new_run.add_picture(img_bytes, width=width, height=height)
# Remove the original run
paragraph._p.remove(run._r)
文本框通常嵌入到
mc:AlternateContent
和 <w:drawing>
元素(等等)中。
您可以使用
xpath('.//wps:txbx//w:txbxContent')
或类似工具来获取它们,然后访问其中的文本。
以下示例省略了几个元素并显示了
wps:txbx
的位置:
<w:p w:rsidR="00CC64EA" w:rsidRDefault="00CC64EA" w:rsidP="00CC64EA">
<w:r>
<mc:AlternateContent>
<mc:Choice Requires="wps">
<w:drawing>
<wp:anchor distT="45720" distB="45720" distL="114300" distR="114300"
simplePos="0" relativeHeight="251659264" behindDoc="0" locked="0"
layoutInCell="1" allowOverlap="1">
<a:graphic
xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
<a:graphicData
uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">
<wps:wsp>
<wps:txbx>
<w:txbxContent>
<w:p w:rsidR="00CC64EA"
w:rsidRDefault="00CC64EA">
<w:r>
<w:t>Content of TextBox</w:t>
</w:r>
</w:p>
</w:txbxContent>
</wps:txbx>
</wps:wsp>
</a:graphicData>
</a:graphic>
</wp:anchor>
</w:drawing>
</mc:Choice>
</mc:AlternateContent>
</w:r>
</w:p>