gpt4 book ai didi

python - 如何使用python从docx文件中提取超链接中的url

转载 作者:行者123 更新时间:2023-12-04 00:06:39 24 4
gpt4 key购买 nike

我一直在尝试找出如何使用 python 从 docx 文件中获取 url,但没有找到任何东西,我尝试了 python-docx 和 python-docx2txt,但 python-docx 似乎只能提取文本,而 python-docx2txt 能够从超链接中提取文本,但不能从 url 本身中提取文本。

最佳答案

我是 Python 的初学者,我的任务是使用 Python 更改 .docx 文档中的每个超链接。感谢 Kiran 的代码,它给了我一些猜测、试验和错误的提示,最终让它工作。这是我拥有并想与其他初学者分享的代码。

# python to change docx URL hyperlinks:
### see: https://stackoverflow.com/questions/40475757/how-to-extract-the-url-in-hyperlinks-from-a-docx-file-using-python

from docx import Document
from docx.opc.constants import RELATIONSHIP_TYPE as RT

print(" This program changes the hyperlinks detected in a word .docx file \n")

docx_file=input(" Pls input docx filename (without .docx): ")

document = Document(docx_file + ".docx")

rels = document.part.rels

for rel in rels:
if rels[rel].reltype == RT.HYPERLINK:
print("\n Origianl link id -", rel, "with detected URL: ", rels[rel]._target)
new_url=input(" Pls input new URL: ")
rels[rel]._target=new_url

out_file=docx_file + "-out.docx"

document.save(out_file)

print("\n File saved to: ", out_file)

谢谢你,腊皮河

关于python - 如何使用python从docx文件中提取超链接中的url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40475757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com