NameError: 全局名称 'unicode' 未定义 - 在 Python 3 中

新手上路,请多包涵

我正在尝试使用一个名为 bidi 的 Python 包。在这个包 (algorithm.py) 的一个模块中,有一些行给我错误,尽管它是包的一部分。

这是几行:

 # utf-8 ? we need unicode
if isinstance(unicode_or_str, unicode):
    text = unicode_or_str
    decoded = False
else:
    text = unicode_or_str.decode(encoding)
    decoded = True

这是错误消息:

 Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    bidi_text = get_display(reshaped_text)
  File "C:\Python33\lib\site-packages\python_bidi-0.3.4-py3.3.egg\bidi\algorithm.py",   line 602, in get_display
    if isinstance(unicode_or_str, unicode):
NameError: global name 'unicode' is not defined

我应该如何重写这部分代码以便它在 Python3 中工作?另外,如果有人在 Python 3 中使用过 bidi 包,请告诉我他们是否发现了类似的问题。我感谢您的帮助。

原文由 TJ1 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 807
2 个回答

Python 3 renamed the unicode type to str , the old str type has been replaced by bytes .

 if isinstance(unicode_or_str, str):
    text = unicode_or_str
    decoded = False
else:
    text = unicode_or_str.decode(encoding)
    decoded = True

您可能需要阅读 Python 3 移植 HOWTO 以获得更多此类详细信息。还有 Lennart Regebro 的 Porting to Python 3: An in-depth guide ,在线免费。

最后但同样重要的是,您可以尝试使用 2to3 工具 来查看它如何为您翻译代码。

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您需要让脚本像我一样继续在 python2 和 3 上工作,这可能会对某人有所帮助

import sys
if sys.version_info[0] >= 3:
    unicode = str

然后可以做例如

foo = unicode.lower(foo)

原文由 Goblinhack 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题