java - 将 unicode 字符传递给 Jython

标签 java python unicode jython

我正在尝试在 Jython 上运行 python 代码,该代码包含一些 Unicode 文字。我想将代码作为字符串传递(而不是从文件加载)。

似乎在调用 exec() 方法时,unicode 字符被转换为“?”字符:

PythonInterpreter interp = new PythonInterpreter(null, new PySystemState());
System.out.println("ā".codePointAt(0)); // outputs 257
interp.exec("print ord(\"ā\")"); // outputs 63

我似乎找不到如何将字符串传递给解释器而不弄乱这些字符的方法。

最佳答案

我无法解释到底发生了什么,但如果将 unicode 对象用作 ord() 的参数并且如果 Python 代码被编译为 PyCode 对象,它对我有用:

import org.python.core.PyException;
import org.python.core.PyCode;
import org.python.util.PythonInterpreter;

public class Main {
  public static void main(String[] args) throws PyException {

    PythonInterpreter interp = new PythonInterpreter();
    System.out.println("ā".codePointAt(0));    // outputs 257
    interp.exec("print ord('ā')");             // outputs 63

    String s = "print ord(u'ā')";
    PyCode code = interp.compile(s);
    interp.exec(code);                         // outputs 257
  }
}

关于java - 将 unicode 字符传递给 Jython,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19126748/

相关文章:

python - 无法在 Debug模式下运行蝗虫

python - 如何创建 SWIG 接口(interface)文件?

string - 为什么 utf-8 编码的 byte\xbd 在 for range 循环中被格式化为 unicode 代码点 fffd?

Java:JTextPane 加载不透明?

java - 如何在 spring boot 远程 shell 中将参数和选项传递给自定义远程 shell 命令?

python - 如何将张量类型值传递给变量的形状参数?

java - 在 XML 中传递 unicode 字符

emacs - 在 GNU Emacs 中查找字符的 Unicode 代码点

具有特权的JVM中的Java文件setWritable

java - 为什么线程不能正常 hibernate ?