NameError:全局名称“unicode”未定义 - 在 Python 3 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19877306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NameError: global name 'unicode' is not defined - in Python 3
提问by TJ1
I am trying to use a Python package called bidi. In a module in this package (algorithm.py) there are some lines that give me error, although it is part of the package.
我正在尝试使用名为 bidi 的 Python 包。在这个包 (algorithm.py) 的一个模块中,有一些行给我错误,尽管它是包的一部分。
Here are the lines:
以下是几行:
# 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
and here is the error message:
这是错误消息:
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
How should I re-write this part of the code so it works in Python3? Also if anyone have used bidi package with Python 3 please let me know if they have found similar problems or not. I appreciate your help.
我应该如何重写这部分代码以便它在 Python3 中工作?另外,如果有人在 Python 3 中使用过 bidi 包,请告诉我他们是否发现了类似的问题。我感谢您的帮助。
采纳答案by Martijn Pieters
Python 3 renamed the unicode
type to str
, the old str
type has been replaced by bytes
.
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
You may want to read the Python 3 porting HOWTOfor more such details. There is also Lennart Regebro's Porting to Python 3: An in-depth guide, free online.
您可能需要阅读Python 3 移植 HOWTO以了解更多此类详细信息。还有 Lennart Regebro 的Porting to Python 3: An in-depth guide,在线免费。
Last but not least, you could just try to use the 2to3
toolto see how that translates the code for you.
最后但并非最不重要的一点是,您可以尝试使用该2to3
工具来查看它如何为您翻译代码。
回答by atm
回答by M.J
Hope you are using Python 3 ,
Str are unicode by default, so please
Replace Unicode
function with String Str
function.
希望你使用的是 Python 3,Str 默认是 unicode,所以请Unicode
用 StringStr
函数替换函数。
if isinstance(unicode_or_str, str): ##Replaces with str
text = unicode_or_str
decoded = False
回答by Neil McGill
If you need to have the script keep working on python2 and 3 as I did, this might help someone
如果您需要像我一样让脚本继续在 python2 和 3 上工作,这可能会对某人有所帮助
import sys
if sys.version_info[0] >= 3:
unicode = str
and can then just do for example
然后可以做例如
foo = unicode.lower(foo)