R语言 夸托中的Python输出高亮显示

2izufjch  于 2023-06-03  发布在  Python
关注(0)|答案(1)|浏览(199)

继续this question关于夸托中的代码输出突出显示:是否也可以使用Python输出来实现这一点?
一个最小的工作示例:

---
title: "Output line highlighting"
format: revealjs
editor: visual
filters:
  - output-line-highlight.lua
---

## Regression Table 

In R:

```{r}
#| class-output: highlight
#| output-line-numbers: "9,10,11,12"
LM <- lm(Sepal.Length ~ Sepal.Width, data = iris)
summary(LM)

Regression Table

In Python:

#| class-output: highlight
#| output-line-numbers: "12,13,14,15,16,17"
import pandas as pd
import statsmodels.api as sm

iris = sm.datasets.get_rdataset('iris').data
LM = sm.OLS(iris['Sepal.Length'], sm.add_constant(iris['Sepal.Width'])).fit()
LM.summary2()

渲染这个文件显示Lua过滤器适用于R输出,但不适用于Python。
cgvd09ve

cgvd09ve1#

Python代码块不支持chunk选项output-class。相反,使用选项classes并使用类output-highlight。对于r代码块,您可以使用class-output: highlightclasses: output-highlight
我已经更新了过滤器,以支持相应的classes: output-highlight

output-line-highlight.lua

function highlight(line_number)
  local highlighter = {
    CodeBlock = function(block)
      if block.classes:includes('highlight') then
        block.classes:insert('has-line-highlights')
        block.attributes["code-line-numbers"] = line_number
        return block
      end
  end
  }
  return highlighter
end

function add_highlight_class()
  return {
    CodeBlock = function(cb)
      if not cb.classes:includes('highlight') then
        cb.classes:insert('highlight')
      end
      return cb
    end
  }
end

function add_class_to_cb()
  return {
    Div = function(el)
      if el.classes:includes('cell-output') then
        return el:walk(add_highlight_class())
      end
    end
  }
end

function highlight_output_div()
  return {
    Div = function(div)
      if div.classes:includes('output-highlight') then
        return div:walk(add_class_to_cb())
      end
    end  
  }
end

function add_output_lnum()
  return {
    Div = function(el)
      if el.classes:includes('cell') then
        line_number = tostring(el.attributes["output-line-numbers"])
        return el:walk(highlight(line_number))
      end
    end
  }
end

function Pandoc(doc)
  if FORMAT == 'revealjs' then
    local doc = doc:walk(highlight_output_div())
    return doc:walk(add_output_lnum())
  end
end

presentation.qmd

---
title: "Output line highlighting"
format: revealjs
filters:
  - output-line-highlight.lua
---

## Regression Table 

In R:

```{r}
#| class-output: highlight
#| output-line-numbers: "9,10,11,12"
LM <- lm(Sepal.Length ~ Sepal.Width, data = iris)
summary(LM)

Regression Table

In Python:

#| classes: output-highlight
#| output-line-numbers: "2,4"

test = [1, 2, 3, 4]

for i in test:
  if i%2 == 0:
    print("this line is highlighted")
  else:
    print("this line is not highlighted")

![](https://i.stack.imgur.com/Gt84Y.png)

相关问题