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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:26:05  来源:igfitidea点击:

NameError: name 'unicode' is not defined

pythonunicodenameerror

提问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, unicodehas 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。