简体   繁体   English

检测jupyter笔记本中的线宽?

[英]Detect line width in jupyter notebook?

For ipython I use this to detect console line width:对于 ipython,我使用它来检测控制台线宽:

    ncols =  int(os.getenv('COLUMNS', 80))

how do I do the same for jupyter notebook from python?我如何为 python 的 jupyter 笔记本做同样的事情?

The width of a jupyter cell can be retrieved from the notebook's style.可以从笔记本的样式中检索 jupyter 单元的宽度。 You can use the browser's development tools to inspect the html or you could use the following code in a notebook cell to retrieve the width of a cell line and then calculate the number of characters it will hold.您可以使用浏览器的开发工具来检查 html,或者您可以在笔记本单元格中使用以下代码来检索单元格行的宽度,然后计算它将容纳的字符数。

The following will:以下将:

  • Use %%html magic to create a canvas and js script.使用%%html魔法创建 canvas 和 js 脚本。
  • look up the div.CodeMirror-lines element and get its font and width.查找div.CodeMirror-lines元素并获取其字体和宽度。
  • set the canvas to the same font as the cell's line element.将 canvas 设置为与单元格的行元素相同的字体。
  • use measureText to measure the length of one character.使用measureText测量一个字符的长度。
  • alert you of the number of characters that will fit within the line's width.提醒您适合行宽的字符数。
%%html
<canvas id="canvas"></canvas>
<script>
    // retrieve the width and font
    var el = document.querySelector("div.CodeMirror-lines")
    var ff = window.getComputedStyle(el, null).getPropertyValue('font');
    var widthpxl = el.clientWidth

    //set up canvas to measure text width
    var can = document.getElementById('canvas');
    var ctx = can.getContext('2d');
    ctx.font = ff;

    //measure one char of text and compute num char in one line
    var txt = ctx.measureText('A');
    alert(Math.floor(widthpxl/txt.width))
    //EDIT: to populate python variable with the output:
    IPython.notebook.kernel.execute("ncols=" + Math.floor(widthpxl/txt.width));
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM