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

TJ1*_*TJ1 120 python unicode bidi nameerror python-3.x

我正在尝试使用名为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
Run Code Online (Sandbox Code Playgroud)

这是错误信息:

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
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ers 197

Python 3将unicode类型重命名为str,旧str类型已被替换为bytes.

if isinstance(unicode_or_str, str):
    text = unicode_or_str
    decoded = False
else:
    text = unicode_or_str.decode(encoding)
    decoded = True
Run Code Online (Sandbox Code Playgroud)

您可能需要阅读Python 3移植HOWTO以获取更多此类详细信息.还有Lennart Regebro的移植到Python 3:一个深入的指南,免费在线.

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

  • @ TJ1:确保你没有删除右括号或某处.代码应该可以正常使用*just*`unicode`替换为`str`. (5认同)

atm*_*atm 16

您可以使用六个库来支持Python 2和3:

import six
if isinstance(value, six.string_types):
    handle_string(value)
Run Code Online (Sandbox Code Playgroud)


Nei*_*ill 12

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

import sys
if sys.version_info[0] >= 3:
    unicode = str
Run Code Online (Sandbox Code Playgroud)

然后可以例如

foo = unicode.lower(foo)
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的想法,很好的答案。只是添加一个细节,如果您使用 `six` 库来管理 Python 2/3 兼容性,您可以使用 `if Six.PY3: unicode = str` 而不是 `sys.version_info` 内容。这对于防止与 Python 3 中未定义的 unicode 相关的 linter 错误也非常有帮助,而不需要特殊的 linter 规则豁免。 (2认同)