Python如何提取docx中的超链接

Python如何解析 <w:t></w:t>中间的内容
用 xml + 正则表达式
如果仅仅使用 for paragraph in document.paragraphs 获取不包含表格的段落时,还应加上.text属性

import re
from docx import Document


def get_paragraph_from_docx(file_name):
    """
    网址:https:blog.csdn.net,这是一段有hyperlink的段落
    这是一段没有hyperlink的段落
    可用于处理包含超链接的文本,但会自动跳过表格
    :param file_name:
    :return:
    """
    text = []
    document = Document(file_name)
    for paragraph in document.paragraphs:
        t_para = u""
        # 有无超链接均可处理
        xml_str = str(paragraph.paragraph_format.element.xml)
        wt_list = re.findall('<w:t[\S\s]*?</w:t>', xml_str)
        for wt in wt_list:
            wt_content = re.sub('<[\S\s]*?>', u"", wt)
            t_para += wt_content
        if t_para:
            t_para = t_para.strip()
            t_para = re.sub('[\s]', '', t_para)
            if t_para:
                text.append(t_para)
    return text
d = docx.Document(./test.docx)
for p in d.paragraphs:
	xml = p.paragraph_format.element.xml
	xml_str = str(xml)
	wt_list = re.findall('<w:t[\S\s]*?</w:t>', xml_str)
	hyperlink = u''
	for wt in wt_list:
		wt_content = re.sub('<[\S\s]*?>', u'', wt)
		hyperlink += wt_content
	print(hyperlink)
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
你可以使用pythonpython-docx库来读取docx文件超链。首先,你需要安装python-docx库,然后使用以下代码来提取docx文件超链: ```python from docx import Document # 打开docx文件 doc = Document('your_docx_file.docx') # 遍历每个段落 for paragraph in doc.paragraphs: # 遍历每个超链 for run in paragraph.runs: if run.hyperlink is not None: # 打印超链和对应的URL print(run.text, run.hyperlink.address) ``` 这段代码会遍历docx文件的每个段落,然后检查每个段落的每个run是否包含超链。如果找到超链,就打印超链的文本和对应的URL。 注意,你需要将`your_docx_file.docx`替换为你实际的docx文件路径。你还需要确保已经安装了python-docx库。 引用提供的代码示例介绍了如何从docx文档提取文件头的信息,并将信息更新到一个xls电子表格,其包含了超链的处理。引用提供了一个相关的参考链,供你进一步学习。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [使用python批量读取word文档并整理关键信息到excel表格的实例](https://download.csdn.net/download/weixin_38676216/13769211)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [python读取excel超链](https://blog.csdn.net/weixin_43815222/article/details/121476491)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值