2

我对编程术语不是很熟悉,所以请耐心等待。

我正在制作一个必须能够保存和读取包含 utf-8 字符的文件文本的语言程序。

我用泡菜

WORDS = [['eat','manger','v'],['drink','boire','v'],
["cake",'le gateau','n'],['coffee','le café','n']]

wordDatabase = open('wordsForProgram.txt','wb')
pickle.dump(WORDS,wordDatabase)
wordDatabase.close()

inFile = open('wordsForProgram.txt','rb')
newList = pickle.load(inFile)
print(newList)

它打印出来:

[['eat', 'manger', 'v'],
['drink', 'boire', 'v'],
['cake', 'le gateau', 'n'],
['coffee', 'le café', 'n']]

脚本中的列表还将“le cafe”更改为“le cafĂ©”。当我将它改回来时,它会再次工作,直到我关闭并重新打开脚本。

谢谢!

4

1 回答 1

1

# -*- coding: utf-8 -*-的文件顶部有吗?

# -*- coding: utf-8 -*-
import pickle
WORDS = [['eat','manger','v'],['drink','boire','v'],
["cake",'le gateau','n'],['coffee','le café','n']]

wordDatabase = open('wordsForProgram.txt','wb')
pickle.dump(WORDS,wordDatabase)
wordDatabase.close()

inFile = open('wordsForProgram.txt','rb')
newList = pickle.load(inFile)

for i in newList:
    for j in i:
        print j

WORDS 和 newList 的输出相同:

eat
manger
v
drink
boire
v
cake
le gateau
n
coffee
le café
n

您也可以尝试使用编解码器模块:

# -*- coding: utf-8 -*-
import pickle
import codecs
WORDS = [['eat','manger','v'],['drink','boire','v'],
["cake",'le gateau','n'],['coffee','le café','n']]

wordDatabase = codecs.open('wordsForProgram.txt', 'w', 'utf-8')
pickle.dump(WORDS,wordDatabase)
wordDatabase.close()

inFile = codecs.open('wordsForProgram.txt','rb')
newList = pickle.load(inFile)

for i in newList:
    for j in i:
        print j
于 2013-08-28T11:27:36.613 回答