有没有更简单的方法来超链接 Jupyter 笔记本中的内部部分以获得 table 的内容?因为语法看起来很难写

Is there an easier way to hyperlink internal sections in a Jupyter notebook for a table of content? as the syntax seem laborious to write

为内容菜单创建 link 的代码是:

<a href="#Section-1">Section 1</a>

在标签的第一部分,标题的空格必须用破折号“-”代替。第二部分只是普通文本,单词之间有空格。

我试过使用:

string.replace(" ", "-")

用破折号替换空格,但是当我在单元格上执行此操作时,字符串带有''。

有什么想法吗?提前致谢。

如果您尝试使用 print() 函数,它将打印保存在变量中的不带引号的字符串:

print(your_string)

但是,我认为为 table 内容创建超链接并避免 do-dashes-in-all-the-words 的更好方法是使用文本输入,将其保存到变量中,使用 replace() 函数和 .format 方法。

如果您想复制此内容并将其粘贴到降价单元格中以制作目录,请尝试以下操作:



import pyperclip as pc
string = input('Enter your string:')
dashed_str = string.replace(" ", "-")
link = ('<a href="#{}">{}</a>'.format(dashed_str, string))
pc.copy(link)

您只需 运行 在单元格上输入超链接的标题,按回车键,结果超链接就会出现在您的剪贴板上,您可以将其粘贴到您正在制作的降价单元格中table 的内容。

我建议您安装并导入 pyperclip 库以将字符串保存到剪贴板,而不是打印它然后复制它——点击次数更少。

另外,您可以使用 markdown 语法链接到以下部分:

[Section title test](#Section-title-test)

所以代码看起来像这样:

import pyperclip as pc
string = input('Enter menu title:')
dashed_str = string.replace(" ", "-")
link = ('[{}](#{})'.format(string, dashed_str))
pc.copy(link)

如果您想改用函数:

def link_menu(x):
    import pyperclip as pc    
    dashed_title = x.replace(" ", "-")
    link = ('[{}](#{})'.format(x, dashed_title))
    return pc.copy(link)

然后你可以调用你的函数,将你想要的超链接字符串作为参数传递,如下所示:

link_menu('Section 4 this is a test')

这将复制到您的剪贴板:

[Section 4 this is a test](#Section-4-this-is-a-test)