Python Unicode 错误
我有一个用Python写的程序,最开始是用Python 2做的,但现在我需要重建它,已经把一些地方改成了Python 3。不过,我的CSV文件加载不进去,出现了...
第一个例子显示“未解决的引用unicode”(我在这里看到过一个解决办法,但根本没用),还显示“未解决的引用file”,有人能帮帮我吗,谢谢!
def load(self, filename):
try:
f = open(filename, "rb")
reader = csv.reader(f)
for sub, pre, obj in reader:
sub = unicode(sub, "UTF-8").encode("UTF-8")
pre = unicode(pre, "UTF-8").encode("UTF-8")
obj = unicode(obj, "UTF-8").encode("UTF-8")
self.add(sub, pre, obj)
f.close()
print
"Loaded data from " + filename + " !"
except:
print
"Error opening file!"
def save(self, filename):
fnm = filename ;
f = open(filename, "wb")
writer = csv.writer(f)
for sub, pre, obj in self.triples(None, None, None):
writer.writerow([sub.encode("UTF-8"), pre.encode("UTF-8"), obj.encode("UTF-8")])
f.close()
print
"Written to " + filename
1 个回答
10
unicode(sub, "UTF-8")
应该是
sub.decode("UTF-8")
在Python3中,str
和unicode
这两种类型合并了,所以不再有内置的unicode
转换操作符了。
Python 3的Unicode使用指南解释了很多不同之处。
自从Python 3.0开始,这个语言有了一个
str
类型,它可以包含Unicode字符。这意味着用"unicode rocks!"
、'unicode rocks!'
或者三重引号字符串语法创建的任何字符串,都会以Unicode的形式存储。
它还解释了encode
和decode
之间的关系。
转换为字节
与
bytes.decode()
相反的方法是str.encode()
,它会返回一个Unicode字符串的bytes
表示,按照请求的编码方式进行编码。
而不是
file(...)
使用open
输入输出文档解释了如何使用open
,以及如何使用with
来确保文件被正确关闭。
在处理文件对象时,使用
with
关键字是个好习惯。这有个好处,就是在代码块结束后,文件会被正确关闭,即使在过程中发生了异常。这样写也比写等效的try-finally块要简洁得多:>>> with open('workfile', 'r') as f: ... read_data = f.read() >>> f.closed True