我正在尝试在 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/