Python NameError: 名称 'unicode' 未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36110598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NameError: name 'unicode' is not defined
提问by Soty
fileMain = open("dictionary_15k.txt", "r")
for line1 in fileMain:
dictWords.append(unicode(line1.strip(), "utf-8"))
When compiled it shows
编译时显示
NameError: name 'unicode' is not defined
回答by Martijn Pieters
There is no such name in Python 3, no. You are trying to run Python 2 code in Python 3. In Python 3, unicode
has been renamed to str
.
Python 3 中没有这样的名字,没有。您正在尝试在 Python 3 中运行 Python 2 代码。在 Python 3 中,unicode
已重命名为str
.
However, you can remove the unicode()
call altogether; open()
produces a file object that alreadydecodes data to Unicode for you. You probably want to tell it what codec to use, explicitly:
但是,您可以unicode()
完全删除呼叫;open()
生成一个已经为您将数据解码为 Unicode的文件对象。您可能想明确地告诉它使用什么编解码器:
fileMain = open("dictionary_15k.txt", "r", encoding="utf-8")
for line1 in fileMain:
dictWords.append(line1.strip())
You may want to switch to Python 2 if your tutorial is written with that version in mind.
如果您的教程是在考虑该版本的情况下编写的,您可能希望切换到 Python 2。