问题: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软件包,请让我知道他们是否发现了类似的问题。我感谢您的帮助。
回答 0
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的“ 移植到Python 3:深入指南”,可免费在线获得。
最后但并非最不重要的一点是,您可以尝试使用该2to3工具查看如何为您翻译代码。
回答 1
如果您需要让脚本像我一样继续在python2和3上工作,这可能会对某人有所帮助
import sys
if sys.version_info[0] >= 3:
    unicode = str然后可以例如
foo = unicode.lower(foo)回答 2
您可以使用6个库同时支持Python 2和3:
import six
if isinstance(value, six.string_types):
    handle_string(value)回答 3
希望您使用的是Python 3,默认情况下Str是unicode,所以请Unicode用String Str函数替换函数。
if isinstance(unicode_or_str, str):    ##Replaces with str
    text = unicode_or_str
    decoded = False
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

