java - Python 和 Java 中相同字符串的不同字符串编码

标签 java python

我有一个文本文件,我正在从中读取行并逐行处理每一行。

我遇到了这条线:

(T)he film is never sure to make a clear point – even if it seeks to rely on an ambiguous presentation.

pointeven 之间,我有三个字符 -

我尝试将字符打印为整数。

在 Java 中:

String input = "(T)he film is never sure to make a clear point – even if it seeks to rely on an ambiguous presentation.";
int[] ords = new int[input.length()];
for (int i = 0; i < ords.length; i++)
    ords[i] = (int) input.charAt(i);

给出:

[40, 84, 41, 104, 101, 32, 102, 105, 108, 109, 32, 105, 115, 32, 110, 101, 118, 101, 114, 32, 115, 117, 114, 101, 32, 116, 111, 32, 109, 97, 107, 101, 32, 97, 32, 99, 108, 101, 97, 114, 32, 112, 111, 105, 110, 116, 32, 8211, 32, 101, 118, 101, 110, 32, 105, 102, 32, 105, 116, 32, 115, 101, 101, 107, 115, 32, 116, 111, 32, 114, 101, 108, 121, 32, 111, 110, 32, 97, 110, 32, 97, 109, 98, 105, 103, 117, 111, 117, 115, 32, 112, 114, 101, 115, 101, 110, 116, 97, 116, 105, 111, 110, 46]

在 Python 中:

def get_ords(string):
    return map(lambda x: ord(x), string)

给出:

[40, 84, 41, 104, 101, 32, 102, 105, 108, 109, 32, 105, 115, 32, 110, 101, 118, 101, 114, 32, 115, 117, 114, 101, 32, 116, 111, 32, 109, 97, 107, 101, 32, 97, 32, 99, 108, 101, 97, 114, 32, 112, 111, 105, 110, 116, 32, 226, 128, 147, 32, 101, 118, 101, 110, 32, 105, 102, 32, 105, 116, 32, 115, 101, 101, 107, 115, 32, 116, 111, 32, 114, 101, 108, 121, 32, 111, 110, 32, 97, 110, 32, 97, 109, 98, 105, 103, 117, 111, 117, 115, 32, 112, 114, 101, 115, 101, 110, 116, 97, 116, 105, 111, 110, 46]

在java的结果中,-这三个字符用8211表示,在python中是表示为 226, 128, 147'\xe2', '\x80', '\x93'。当我在 java 和 python 中处理它时,这种差异导致了不同的结果。

我还注意到,如果我从字符串中删除 -,两者的结果是相同的。

是否可以在不删除特殊字符的情况下解决这个问题。

最佳答案

您可能没有将它用作 Python 中的 unicode 字符串(Python 2 中的 u 前缀)。

这可以通过以下代码(使用示例的相关部分)来说明:

# -*- coding: utf-8 -*-

x = u"t – e"
y = "t – e"

def get_ords(s):
    return map(lambda x: ord(x), s)

print "x: %s" % (get_ords(x),)
print "y: %s" % (get_ords(y),)

结果是:

x: [116, 32, 8211, 32, 101]
y: [116, 32, 226, 128, 147, 32, 101]

有关 Unicode 的 Python 文档应该很有趣:https://docs.python.org/2/howto/unicode.html

从文件读取时,可以使用codecs ,否则,您不会以 Unicode 格式读取文件:

import codecs

with codecs.open('test.txt','r','utf-8') as f:
    x = f.read()

with open('test.txt','r') as f:
    y = f.read()

(这产生与上述相同的结果。)

请注意,在 Java 中,用于读取的编码也可能取决于 file.encoding 系统属性的值。 (这取决于您如何读取文件,请参阅:https://docs.oracle.com/javase/tutorial/i18n/text/stream.html)

关于java - Python 和 Java 中相同字符串的不同字符串编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41625718/

相关文章:

Java 全局变量未在新类中更新

java - 如何在 NetBeans 视觉库中获取鼠标位置?

python - [Python+ Bokeh ] : how to make a needle dial?

java - 新的构造函数和函数

java - SQLite插入函数/方法参数参数太多,如何重构?

java - 我可以使用 JNI 调用 Python 库吗?

python - 捕获文件名

python - 为什么我的 Django 站点在使用此 URL 解析器检查时不返回 404?

python - 如何从 python 数据框字段中删除 "?"

java - jackson 对象映射器关于字段值?