我正在try 使用一个名为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将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,免费在线.

最后但并非最不重要的一点是,您可以try 使用2to3 tool来查看它如何为您翻译代码.

Python-3.x相关问答推荐

如何从Django连接到Neo4J s AuraDB(免费层)?'

我想判断df_entry_log[AM_PM],并根据测试填充列

十进制浮点数到整型的转换错误

我可以设置树视图层次 struct 按钮吗?

对大型数据框中的选定列进行重新排序

通过在不重新索引的情况下采用最高概率的百分比,有效地转换 0/1 列表中的概率列表

pip install saxonche v 12.1.0 产生 FileNotFoundError

Python - 如何从同一台客户端机器运行多个Flask应用程序

你如何表达一个没有参数的 Python Callable?

错误:预期语句,发现 py:Dedent

Pytorch 的随机 Select ?

Python 3 list(dictionary.keys()) 引发错误.我究竟做错了什么?

Python - For 循环数百万行

multiprocessing.Queue 中的 ctx 参数

如何用pymongo连接远程mongodb

python 3.4版不支持'ur'前缀

为什么中断比引发异常更快?

为 True 相交两个布尔数组

如何从 Python 3 导入 FileNotFoundError?

Pylint 中的模块PyQt5.QtWidgets错误中没有名称QApplication