我正在使用 python-docx 将 word 文档转换为 txt 文件。文档中有一些词有超链接。我不需要链接,我只需要文本本身。但是当我使用段落来阅读它时,文本就消失了。
elements = []
for block in fp.element.body:
if block.__class__.__name__ == 'CT_P':
elements.append(('paragraph', block))
elif block.__class__.__name__ == 'CT_Tbl':
elements.append(('table', block))
for index, type_el in enumerate(elements):
element_type, element = type_el[0], type_el[-1]
# write paragraph into the txt file
if element_type == 'paragraph':
paragraph = Paragraph(parse_xml(element.xml), parent=None)
img = paragraph._element.xpath('.//pic:pic')
if not img:
txt = paragraph.text
if txt != "":
txt_file.write(txt + "\n")
超链接表示为 Run 对象。您可以通过以下代码获取超链接文本:
for run in paragraph.runs:
if "hyperlink" in run._element.xml:
txt_file.write(run.text + "\n")
这已在
python-docx==1.0.0
中得到纠正,其中 Paragraph.text
包括超链接文本。
在撰写本文时,它的名称为
pip install python-docx==1.0.0rc1
,但应该会在 2023 年 11 月 1 日之前以 pip install python-docx
的形式提供。
当您需要知道超链接出现在段落文本其余部分中的位置时,它还允许直接访问超链接:
from docx.text.hyperlink import Hyperlink
from docx.text.run import Run
...
for item in paragraph.iter_inner_content():
if isinstance(item, Run):
...
elif isinstance(item, Hyperlink):
...