Python Unicode错误

use*_*197 3 python unicode function

我有一个用python 2构建的python程序,但是现在我必须重建它并且已经将某些内容更改为python3,但是以某种方式,我的csv没有被加载并说...

第一个示例的未解析参考unicode(我已经在这里看到了一个解决方案,但根本没有用),并说未解析参考文件,有人可以帮助我提前吗;)

 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
Run Code Online (Sandbox Code Playgroud)

Mik*_*uel 7

unicode(sub, "UTF-8")
Run Code Online (Sandbox Code Playgroud)

应该

sub.decode("UTF-8")
Run Code Online (Sandbox Code Playgroud)

Python3统一了str和unicode类型,因此不再有内置的强制转换unicode运算符。


Python 3 Unicode HOWTO解释了很多差异。

因为Python 3.0,语言的特征在于含有Unicode字符的STR型,这意味着使用创建的任何串"unicode rocks!",'unicode rocks!'或三引号字符串语法被存储为Unicode。

并说明如何encode和decode相互之间的关系

转换为字节

相反的方法bytes.decode()是str.encode(),该方法返回以bytes请求的编码方式编码的Unicode字符串的表示形式。


代替

file(...)
Run Code Online (Sandbox Code Playgroud)

使用 open

在I / O文档解释如何使用open以及如何使用with,以确保它被关闭。

在处理文件对象时,最好使用with关键字。这样做的好处是,即使在执行过程中引发了异常,文件在其套件完成后也将正确关闭。它也比编写等效的try-finally块要短得多:

 >>> with open('workfile', 'r') as f:
 ...     read_data = f.read()
 >>> f.closed
 True
Run Code Online (Sandbox Code Playgroud)