【问题标题】:How can I copy to the clipboard the output of a cell in a Jupyter notebook?如何将 Jupyter 笔记本中单元格的输出复制到剪贴板?
【发布时间】:2017-10-29 00:21:30
【问题描述】:

如何将 Jupyter 笔记本中单元格的输出复制到剪贴板,而无需通过拖放选择它?

【问题讨论】:

  • 不完全正确,因为您需要用鼠标进行选择,但我发现这很有帮助。您可以使用Shift+Right mouse button 访问浏览器的本机上下文菜单。 (适用于 Chrome 76,并且应该适用于大多数现代浏览器)。

标签: python clipboard jupyter-notebook


【解决方案1】:

Jupyter notebook 在浏览器中运行,因此您可以使用一些 javascript 来选择单元格并将其复制到剪贴板。经过反复试验,我想出了这个书签:

javascript:(function%20()%20%7B%20function%20SelectText(element)%20%7B%20var%20range%3B%20var%20selection%3B%20if%20(document.body.createTextRange)%20%7B%20range%20%3D%20document.body.createTextRange()%3B%20range.moveToElementText(element)%3B%20range.select()%3B%20copy2clipboard(range.text%2C%20element.innerHTML)%3B%20document.getSelection().removeAllRanges()%3B%20%7D%20else%20if%20(window.getSelection)%20%7B%20selection%20%3D%20window.getSelection()%3B%20range%20%3D%20document.createRange()%3B%20range.selectNodeContents(element)%3B%20selection.removeAllRanges()%3B%20selection.addRange(range)%3B%20copy2clipboard(selection.toString()%2C%20element.innerHTML)%3B%20selection.removeAllRanges()%3B%20%7D%20%7D%3B%20function%20copy2clipboard(text%2C%20html)%20%7B%20function%20listener(e)%20%7B%20e.clipboardData.setData('text%2Fplain'%2C%20text)%3B%20e.clipboardData.setData('text%2Fhtml'%2C%20html)%3B%20e.preventDefault()%3B%20%7D%20document.addEventListener('copy'%2C%20listener)%3B%20document.execCommand('copy')%3B%20document.removeEventListener('copy'%2C%20listener)%3B%20%7D%3B%20%24('%23notebook-container').on('mouseenter'%2C%20'.input%2C%20.output_wrapper'%2C%20function%20()%20%7B%20if%20(%24(this).find('i%3Alast').length)%20%7B%20%24(this).find('i%3Alast').show()%3B%20%7D%20else%20%7B%20%24(this).css(%7B%20'position'%3A%20'relative'%20%7D).append(%24('%3Ci%20style%3D%22position%3Aabsolute%3B%20top%3A7px%3B%20left%3A%207px%3B%22%20class%3D%22fa-copy%20fa%22%3E%3C%2Fi%3E').on('click'%2C%20function%20()%20%7B%20SelectText(%24(this).parent().find('.input_area%2C%20.output')%20%5B0%5D)%3B%20%24(this).slideUp()%3B%20%7D))%3B%20%7D%20%7D)%3B%20%24('%23notebook-container').on('mouseleave'%2C%20'.input%2C%20.output_wrapper'%2C%20function%20()%20%7B%20%24(this).find('i%3Alast').hide()%3B%20%7D)%3B%20%7D)%20()%3B

将其添加到您的书签并在笔记本页面上运行。

工作原理

  1. 对于每个 inputoutput 单元格,它会添加一个小复制图标,在悬停时显示。
  2. 单击复制图标选择相应的单元格内容,将其发送到剪贴板,然后取消选择。内容以 text/plaintext/html 格式复制,因此可用于复制带有格式的文本、表格、图像和绘图。
  3. 应对后,图标消失以提供一些反馈,并在下一次悬停事件时显示。

它应该适用于任何现代浏览器,包括 IE11。

这里是解码源:

(function () {
  function SelectText(element) {
    var range;
    var selection;
    if (document.body.createTextRange) {
      range = document.body.createTextRange();
      range.moveToElementText(element);
      range.select();
      copy2clipboard(range.text, element.innerHTML);
      document.getSelection().removeAllRanges();
    } else if (window.getSelection) {
      selection = window.getSelection();
      range = document.createRange();
      range.selectNodeContents(element);
      selection.removeAllRanges();
      selection.addRange(range);
      copy2clipboard(selection.toString(), element.innerHTML);
      selection.removeAllRanges();
    }
  };
  function copy2clipboard(text, html) {
    function listener(e) {
      e.clipboardData.setData('text/plain', text);
      e.clipboardData.setData('text/html', html);
      e.preventDefault();
    }
    document.addEventListener('copy', listener);
    document.execCommand('copy');
    document.removeEventListener('copy', listener);
  };
  $('#notebook-container').on('mouseenter', '.input, .output_wrapper', function () {
    if ($(this).find('i:last').length) {
      $(this).find('i:last').show();
    } else {
      $(this).css({
        'position': 'relative'
      }).append($('<i style=\"position:absolute; top:7px; left: 7px;\" class=\"fa-copy fa\"></i>').on('click', function () {
        SelectText($(this).parent().find('.input_area, .output') [0]);
        $(this).slideUp();
      }));
    }
  });
  $('#notebook-container').on('mouseleave', '.input, .output_wrapper', function () {
    $(this).find('i:last').hide();
  });
}) ();

书签是通过从代码中删除换行符并通过encodeURIComponent() 函数运行来创建的。

旧答案

有几种方法可以使用 tkinter、win32 或 ctypes 在 python 中将数据复制到剪贴板。但如果你使用的是 Jupyter notebook,你可能也在使用 pandas。

import pandas as pd
df = pd.DataFrame(['Copy me to clipboard'])
df.to_clipboard(index=False,header=False)

【讨论】:

  • 我同意 - 有没有办法只复制粘贴而不选择整个页面?
  • 另外,如果您的 jupyter 服务器在另一台机器上运行,这将不起作用。
  • @FranckDernoncourt 我添加了更好的解决方案。
  • 天啊,你让我的生活变得如此美好!这还可以将表格(熊猫!)合理地复制+粘贴到 Evernote 和 OneNote 之类的工具中,您确实需要这些工具的 HTML。
  • 我喜欢这个!这是一个衬里:pd.DataFrame(['Copy me to clipboard']).to_clipboard(index=False,header=False),因此您无需创建保留的数据框。
【解决方案2】:

您可以尝试使用pyperclip - 一个将字符串复制到系统剪贴板的第三方包。

给定

import pyperclip as clip


# Sample Data
res = [(str(x*100), x) for x in range(1, 10)]
res

输出

[('100', 1), ('200', 2), ('300', 3),
 ('400', 4), ('500', 5), ('600', 6), 
 ('700', 7), ('800', 8), ('900', 9)]

代码

clip.copy(f"{res}")
#clip.copy("{}".format(res))                           # python < 3.6
clip.paste()                                           # or Ctrl + V

输出

[('100', 1), ('200', 2), ('300', 3),
 ('400', 4), ('500', 5), ('600', 6),
 ('700', 7), ('800', 8), ('900', 9)]

【讨论】:

    【解决方案3】:

    我使用 Jupyter 实验室。您可以右键单击要复制的输出单元格并选择

    为输出创建新视图。这会将输出放在单独的屏幕中。在新的输出屏幕上,它将让您使用 CRTL + C 或右键单击进行复制。

    希望这会有所帮助。

    【讨论】:

      【解决方案4】:

      在下面的示例中,不会输出实际文本(尽管如果更改函数的第 6 行可能会输出),而是显示一行确认剪贴板上已提供多行可用的行。

      all_data_str 是一个字符串,其内容将在剪贴板上可用,请编写您自己的生成函数,名为 dump_data_array。

      当用户单击调用该函数的按钮时触发粘贴操作:

      def on_button_clipboard(b):
          out_data.clear_output()
          all_data_str=dump_data_array(da)
          with out_data:
              lineCount=all_data_str.count('\n')-1;
              html_div = '<div id="pasting_to_clipboard">'+str(lineCount)+' lines pasted, you can now ^V into Excel</div>'
              display(HTML(html_div))
              js = """<script>
      function copyToClipboard(text) {
          var dummy = document.createElement("textarea");
          document.body.appendChild(dummy);
          dummy.value = text;
          dummy.select();
          document.execCommand("copy");
          document.body.removeChild(dummy);
      }
              </script>"""
              display(HTML(js))
              js2 = "<script>copyToClipboard(`" + all_data_str + "`);</script>"
              display(HTML(js2))
      

      【讨论】:

        【解决方案5】:

        在 Ubuntu 19.10 / Firefox 浏览器上,我可以通过连续点击 3 次来将输出单元格内容作为一个整体选择,然后像往常一样 CTRL+C 进行复制。 p>

        【讨论】:

          【解决方案6】:

          这可以在 Jupyter Lab 3.1.4 中运行。右键单击(或在 Mac 触控板上用两根手指单击)单元格输出区域。

          会弹出一个菜单,其中顶部的选项是“复制输出到剪贴板”。

          【讨论】:

            猜你喜欢
            • 2017-06-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-04-28
            • 1970-01-01
            相关资源
            最近更新 更多