gpt4 book ai didi

python - 如何使用代码单元格打印功能仅在 Jupyter Notebook 中呈现超链接加文本?

转载 作者:行者123 更新时间:2023-12-05 02:44:39 26 4
gpt4 key购买 nike

以下链接提供了一种在 Jupyter 笔记本代码单元内的 python3 print() 函数内呈现 HTML URL 的方法,

https://github.com/jupyterlab/jupyterlab/issues/7393#issue-510053776 ,

它定义了一个自定义 URL 类,

"""URL Wrapper."""

from dataclasses import dataclass

@dataclass(frozen=True)
class Url:
"""Wrapper around a URL string to provide nice display in IPython environments."""

__url: str

def _repr_html_(self):
"""HTML link to this URL."""
return f'<a href="{self.__url}">{self.__url}</a>' # problem here (*)

def __str__(self):
"""Return the underlying string."""
return self.__url

评论员指出,必须使用 str(url()) 才能获得所需的结果。

与(我认为)现在内置的渲染不同,我正在尝试使用这个自定义类:

linker = lambda my_string: str(Url('https://www.google.com/%s' % my_string))
print('URL for my_string is here',linker('search'))

我希望 linker('search') 呈现为带有完整超链接 ( https://www.google.com/search ) 的字符串“search”。内置行为不呈现“搜索”,而是呈现完整的超链接,我找不到成功修改自定义类来执行此操作的方法。在上面的 (*) 行,我尝试过:

return f'<a href="{self.__url}">{self.__url}</a>'
return f'<a href="{self.__url}">{"test_text"}</a>'

等但到目前为止都是徒劳的。

这个答案有点帮助,但没有根据我的要求明确使用打印功能:https://stackoverflow.com/a/43254984/1021819

我错过了什么?

最佳答案

这有点卡顿,但似乎有效:


class RenderHyperlink(object):
def __init__(self, key, link, *args):
link = link + "/" if not link.endswith("/") else link

for arg in args:
link += arg + "/"

self.__url = "<a href={}>{}</a>".format(link, key)

def __repr__(self):
from IPython.core.display import display, HTML
display(HTML(self.__url))
return "" # hacky way to return a string despite not returning anything


# notice that you can also add other parameters to the link
print(RenderHyperlink("search", "https://www.google.com/search", "hello"))

输出:该链接指向“https://www.google.com/search/hello/” enter image description here

关于python - 如何使用代码单元格打印功能仅在 Jupyter Notebook 中呈现超链接加文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66335012/

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