【问题标题】:name unicode not defined python3名称 unicode 未定义 python3
【发布时间】:2016-12-01 11:32:17
【问题描述】:

我一直在尝试运行此代码 这是错误

 File "C:/hari/Academics/python/py programs/gui qt4/book/calculator.py", line 27, in updateUi
    text = unicode(self.lineedit.text(),'utf-8')
NameError: name 'unicode' is not defined

代码:

from __future__ import division
from math import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

class Form(QDialog):
    def __init__(self,parent =None):
    super(Form,self).__init__(parent)
    self.browser =QTextBrowser()
    self.lineedit =QLineEdit("type an exp")
    self.lineedit.selectAll()
    layout=QVBoxLayout()
    layout.addWidget(self.browser)
    layout.addWidget(self.lineedit)
    self.setLayout(layout)
    self.lineedit.setFocus()
    self.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateUi)
    self.setWindowTitle("Calculate")
def updateUi(self):
    try:
        text = unicode(self.lineedit.text())
        print(type(text))
        self.browser.append(text+" = <b>"+eval(text)+"</b>" )

    except:
        self.browser.append("<font color=red>"+ text + " is invalid</font>")
app=QApplication(sys.argv)
f=Form()
f.show()
app.exec_()

【问题讨论】:

  • 顺便说一句:1) 从不使用裸except:。始终指定要捕获的异常,否则它甚至会捕获KeyboardInterrupt 并且还可以轻松隐藏错误。 2) 从不对用户插入的文本调用eval。如果要将文本转换为数字,请使用 int(text)float(text)。如果您想允许任何类型的 literal,请使用 ast 包中的 literal_eval

标签: pyqt4 python-3.4 python-unicode


【解决方案1】:

在 python 3 中,字符串默认是 unicode。

删除unicode函数,替换为str

https://docs.python.org/3.0/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit

还有一个小秘诀可以让代码兼容 python 2 和 3:

try:
    unicode        # check if unicode is defined
except NameError:  # not found: python 3: replace by str
    unicode = str

就像 Bakuriu 在他的评论中所说,永远不要使用裸的 except:

喜欢:

except Exception as e:
    print("Problem "+repr(e))
    # the line below requires some HTML normalization or resulting
    # html could be incorrect
    import re
    ne = re.sub("[^\w]"," ",str(e))
    self.browser.append("<font color=red>"+ne+"</font>")

现在你已经显示了真正的/下一个异常。

【讨论】:

  • 试过了,兄弟,但它仍然进入异常块,str 说 text = str(self.lineedit.text(),'utf-8') TypeError: 不支持解码 str跨度>
  • 在将 Python 3 与 PyQt 一起使用时,您不需要 unicodestr,因为 QString 会自动转换为 python 字符串。只需:text = self.lineedit.text().
  • 您是否遇到了异常(如果您遵循了我们关于异常详细信息的建议),如果是,您可以与我们分享吗?
【解决方案2】:

希望你使用的是 Python 3,所以请替换

Unicode 函数与字符串 Str 函数。

def updateUi(self):
    try:
        text = str(self.lineedit.text())  ##replaced here

【讨论】:

    猜你喜欢
    • 2016-07-06
    • 2019-07-08
    • 2018-11-25
    • 2013-10-29
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    相关资源
    最近更新 更多