在 Java 中使用 Pygments

感谢 Jython,我们可以在 Java 中使用 Pygments。

本页是一个简单的教程,旨在让您了解其工作原理。您可以在 Jython 文档 中找到更高级的用法。

从 1.5 版本开始,Pygments 作为 JAR 包部署在 Maven 中央仓库 中,Jython 也是如此,这使得创建 Java 项目变得更加容易。

以下是一个运行 Pygments 项目的 Maven pom.xml 文件示例

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>example</groupId>
  <artifactId>example</artifactId>
  <version>1.0-SNAPSHOT</version>
  <dependencies>
    <dependency>
      <groupId>org.python</groupId>
      <artifactId>jython-standalone</artifactId>
      <version>2.5.3</version>
    </dependency>
    <dependency>
      <groupId>org.pygments</groupId>
      <artifactId>pygments</artifactId>
      <version>1.5</version>
      <scope>runtime</scope>
    </dependency>
  </dependencies>
</project>

以下 Java 示例

PythonInterpreter interpreter = new PythonInterpreter();

// Set a variable with the content you want to work with
interpreter.set("code", code);

// Simple use Pygments as you would in Python
interpreter.exec("from pygments import highlight\n"
    + "from pygments.lexers import PythonLexer\n"
    + "from pygments.formatters import HtmlFormatter\n"
    + "\nresult = highlight(code, PythonLexer(), HtmlFormatter())");

// Get the result that has been set in a variable
System.out.println(interpreter.get("result", String.class));

将输出类似于以下内容:

<div class="highlight">
<pre><span class="k">print</span> <span class="s">&quot;Hello World&quot;</span></pre>
</div>