NameError:全局名称“unicode”未定义-在Python 3中
- 2025-03-05 09:16:00
- admin 原创
- 35
问题描述:
我正在尝试使用一个名为 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:Python33libsite-packagespython_bidi-0.3.4-py3.3.eggidialgorithm.py", line 602, in get_display
if isinstance(unicode_or_str, unicode):
NameError: global name 'unicode' is not defined
我应该如何重写这部分代码以使其在 Python3 中工作?此外,如果有人在 Python 3 中使用过 bidi 包,请告诉我他们是否发现类似的问题。感谢您的帮助。
解决方案 1:
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 移植指南以了解更多此类详细信息。此外,还有 Lennart Regebro 的移植到 Python 3:深入指南,可免费在线阅读。
最后但同样重要的一点是,您可以尝试使用该2to3
工具来了解它如何为您翻译代码。
解决方案 2:
如果你需要让脚本像我一样继续在 python2 和 3 上运行,这可能会对某些人有所帮助
import sys
if sys.version_info[0] >= 3:
unicode = str
然后就可以例如
foo = unicode.lower(foo)
解决方案 3:
您可以使用六个库来支持 Python 2 和 3:
import six
if isinstance(value, six.string_types):
handle_string(value)
解决方案 4:
可以用unicode
来替换 Python 3 中u''.__class__
缺失的unicode
类。对于 Python 2 和 3,你可以使用构造
isinstance(unicode_or_str, u''.__class__)
或者
type(unicode_or_str) == type(u'')
根据您的进一步处理,考虑不同的结果:
Python 3
>>> isinstance(u'text', u''.__class__)
True
>>> isinstance('text', u''.__class__)
True
Python 2
>>> isinstance(u'text', u''.__class__)
True
>>> isinstance('text', u''.__class__)
False
解决方案 5:
希望您使用的是 Python 3,Str 默认是 unicode,因此请Unicode
用 StringStr
函数替换函数。
if isinstance(unicode_or_str, str): ##Replaces with str
text = unicode_or_str
decoded = False
解决方案 6:
如果使用第三方库unicode
并且您无法更改其源代码,则可以使用以下 monkey patchstr
来代替unicode
模块:
import <module>
<module>.unicode = str
解决方案 7:
你可以在 python2 或 python3 中使用它
type(value).__name__ == 'unicode':
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD