如何仅使用codecell打印功能在Jupyter笔记本中呈现超链接和文本?

2024-04-29 04:11:12 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的链接提供了一种在Jupyter笔记本代码单元中的python3print()函数中呈现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')呈现为字符串“search”,后面是完整的超链接(https://www.google.com/search)。内置行为不会呈现“搜索”,而是呈现完整的超链接,我无法找到一种方法来成功修改自定义类来实现这一点。在上面的第(*)行,我尝试过:

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

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

这个答案有点帮助,但没有按照我的要求明确使用print函数:https://stackoverflow.com/a/43254984/1021819

我错过了什么


Tags: 方法函数httpsselfcomurlsearchstring
1条回答
网友
1楼 · 发布于 2024-04-29 04:11:12

这有点僵硬,但似乎有效:


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

相关问题 更多 >