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

2024-05-18 15:34:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用一个名为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包,请告诉我他们是否发现了类似的问题。谢谢你的帮助。


Tags: ortextinpygetif错误line
3条回答

如果你需要像我一样让脚本继续处理python2和3,这可能有助于

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

然后就可以举个例子

foo = unicode.lower(foo)

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

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

最后但并非最不重要的是,您可以尝试使用^{} tool来查看如何为您翻译代码。

可以使用six库同时支持Python 2和3:

import six
if isinstance(value, six.string_types):
    handle_string(value)

相关问题 更多 >

    热门问题