难以使用Python转换转义的UTF-8

时间:2014-12-05 09:56:49

标签: python-3.x utf-8 codec

我无法理解为什么一个功能起作用而另一个功能不起作用。我已经尝试将aristotle.txt文件编码为utf-8和其他编码,但它仍然只输出转义的代码。代码如下所示。

import codecs

def convert_to_utf8_1(from_file, to_file):
    to_file = codecs.open(to_file,'w','utf8')
    from_file = codecs.open(from_file, 'r', 'utf8') 
    #from_file = open(from_file, 'r') 

    for line in from_file:
        to_file.write(line)
    to_file.close()

def convert_to_utf8_2(from_string, to_file):
    to_file = codecs.open(to_file,'w','utf8')
    to_file.write(from_string)
    to_file.close()

if __name__ == '__main__':
     a = "Aristotle$$$$Aristotle (/\u02C8\u00E6r\u026A\u02CCst\u0252t\u0259l/; Greek: \u1F08\u03C1\u03B9\u03C3\u03C4\u03BF\u03C4\u03AD\u03BB\u03B7\u03C2 [aristot\u00E9l\u025B\u02D0s], Aristot\u00E9l\u0113s; 384 \u2013 322 BCE) was a Greek philosopher and scientist born in Stagirus, northern Greece, in 384 BCE. His father, Nicomachus, died when Aristotle was a child, whereafter Proxenus of Atarneus became his guardian. At eighteen, he joined Plato's Academy in Athens and remained there until the age of thirty-seven (c. 347 BCE)."
     convert_to_utf8_1("aristotle.txt", "test1.txt")
     convert_to_utf8_2(a, "test2.txt")


#########################OUTPUT FROM test1.txt###############################
#Aristotle$$$$Aristotle (/\u02C8\u00E6r\u026A\u02CCst\u0252t\u0259l/; Greek: #\u1F08\u03C1\u03B9\u03C3\u03C4\u03BF\u03C4\u03AD\u03BB\u03B7\u03C2 [aristot\u00E9l\u025B\u02D0s], Aristot\u00E9l\u0113s; 384 #\u2013 322 BCE) was a Greek philosopher and scientist born in Stagirus, northern Greece, in 384 BCE. His father, Nicomachus, died #when Aristotle was a child, whereafter Proxenus of Atarneus became his guardian. At eighteen, he joined Plato's Academy in Athens #and remained there until the age of thirty-seven (c. 347 BCE).
#########################OUTPUT FROM test2.txt###############################
#Aristotle$$$$Aristotle (/ˈærɪˌstɒtəl/; Greek: Ἀριστοτέλης [aristotélɛːs], Aristotélēs; 384 – 322 BCE) was a Greek philosopher and #scientist born in Stagirus, northern Greece, in 384 BCE. His father, Nicomachus, died when Aristotle was a child, whereafter #Proxenus of Atarneus became his guardian. At eighteen, he joined Plato's Academy in Athens and remained there until the age of #thirty-seven (c. 347 BCE).

请求几行的十六进制:

0000-0010:  41 72 69 73-74 6f 74 6c-65 24 24 24-24 41 72 69  Aristotl e$$$$Ari
0000-0020:  73 74 6f 74-6c 65 20 28-2f 5c 75 30-32 43 38 5c  stotle.( /\u02C8\

0 个答案:

没有答案