【问题标题】:NameError: name 'unicode' is not defined [duplicate]NameError:名称'unicode'未定义[重复]
【发布时间】:2016-07-06 18:07:38
【问题描述】:
fileMain = open("dictionary_15k.txt", "r")
for line1 in fileMain:
    dictWords.append(unicode(line1.strip(), "utf-8"))

编译后显示

NameError: name 'unicode' is not defined

【问题讨论】:

  • @Signal:不,如果这是 Python 2,他们就不必这样做,因为它是内置的。 OP 显然正在使用 Python 3 运行 Python 2 代码。
  • @MartijnPieters 哇,谢谢。

标签: python unicode nameerror


【解决方案1】:

Python 3 中没有这样的名称,没有。您正在尝试在 Python 3 中运行 Python 2 代码。在 Python 3 中,unicode 已重命名为 str

但是,您可以完全删除 unicode() 调用; open() 生成一个文件对象,已经为您将数据解码为 Unicode。您可能想明确地告诉它使用什么编解码器:

fileMain = open("dictionary_15k.txt", "r", encoding="utf-8")
for line1 in fileMain:
    dictWords.append(line1.strip())

如果您的教程是使用 Python 2 编写的,您可能希望切换到 Python 2。

【讨论】:

    猜你喜欢
    • 2018-08-01
    • 2020-06-17
    • 2015-10-22
    • 2016-05-12
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    相关资源
    最近更新 更多