我有一个文本文件,我正在从中读取行并逐行处理每一行。
我遇到了这条线:
(T)he film is never sure to make a clear point – even if it seeks to rely on an ambiguous presentation.
在 point
和 even
之间,我有三个字符 、
-
和 。
我尝试将字符打印为整数。
在 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/