Python Unicode错误

3
我有一个用Python编写的程序,原本是针对Python 2建立的,现在我需要重建它,并且已经将一些内容更改为Python 3,但不知何故,我的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
1个回答

10
unicode(sub, "UTF-8")

应该是

sub.decode("UTF-8")

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

Python 3的Unicode HOWTO解释了许多不同之处。

自Python 3.0以来,该语言具有包含Unicode字符的str类型,这意味着使用"unicode rocks!"'unicode rocks!'或三引号字符串语法创建的任何字符串都存储为Unicode。

并解释了encodedecode之间的关系

转换为字节

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


代替

file(...)

使用open

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

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:

 >>> with open('workfile', 'r') as f:
 ...     read_data = f.read()
 >>> f.closed
 True

那个有效;)谢谢关于文件名,你能解释一下吗? - user3460197
没问题,非常感谢。只是有一件奇怪的事情,它按照您所说的所有步骤进行操作,但它仍然无法读取我的CSV文件。但正如我所说,您的帮助非常棒,朋友。我已经点赞了。 - user3460197
出现了两个看起来有些奇怪的错误Traceback (most recent call last): File "Main.py", line 120, in <module> lg.save(path) File "LeGraph.py", line 188, in save writer.writerow([sub.encode("UTF-8"), pre.encode("UTF-8"), obj.encode("UTF-8")]) TypeError: 'str' 不支持缓冲区接口 - user3460197

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接