{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 使用 {class}`IPython.display.Code` 高亮代码" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from IPython.display import Code" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
a = 12\n",
       "b = 24\n",
       "c = a + b\n",
       "print(c)\n",
       "
\n" ], "text/latex": [ "\\begin{Verbatim}[commandchars=\\\\\\{\\}]\n", "\\PY{n}{a} \\PY{o}{=} \\PY{l+m+mi}{12}\n", "\\PY{n}{b} \\PY{o}{=} \\PY{l+m+mi}{24}\n", "\\PY{n}{c} \\PY{o}{=} \\PY{n}{a} \\PY{o}{+} \\PY{n}{b}\n", "\\PY{n+nb}{print}\\PY{p}{(}\\PY{n}{c}\\PY{p}{)}\n", "\\end{Verbatim}\n" ], "text/plain": [ "\n", "a = 12\n", "b = 24\n", "c = a + b\n", "print(c)" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "code = \"\"\"\n", "a = 12\n", "b = 24\n", "c = a + b\n", "print(c)\n", "\"\"\"\n", "\n", "Code(code, language=\"python\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "也可以自定义高亮:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "def code2html(code):\n", " \"\"\"Helper function to use pygments to turn the code string into highlighted html.\"\"\"\n", " import pygments\n", " from pygments.lexers import Python3Lexer\n", " from pygments.formatters import HtmlFormatter\n", " formatter = HtmlFormatter()\n", " html = pygments.highlight(code, Python3Lexer(), formatter)\n", " style = formatter.get_style_defs(\".highlight\")\n", " return f\"\\n{html}\\n\"" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "
a = 12\n",
       "b = 24\n",
       "c = a + b\n",
       "print(c)\n",
       "
\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import HTML\n", "\n", "HTML(code2html(code))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3.10.4 ('mlc': conda)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.4" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "d8a760899c905ec5a15e0d212432af25d7f0b614c7ae634224dffa77837bb03c" } } }, "nbformat": 4, "nbformat_minor": 2 }