我对编写行话不是很熟悉,所以请耐心等待。
我正在编写一个语言程序,必须能够保存和读取包含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']]
脚本中的列表也将'lecafé'更改为'lecafĂĂ'。当我将其更改回来时,它再次起作用,直到我关闭并重新打开脚本。
谢谢!
答案 0 :(得分: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