How to convert Arabic text from PyQt4 to UTF-8

六月ゝ 毕业季﹏ 提交于 2019-12-11 12:08:01

问题


I made a Python 2 GUI application with PyQt4 that has two entries. The first takes the file name, and the second takes the text to write in the file.

I want to enter Arabic text in both of them, so I wrote this function:

def makefile(self):
    self.name_file=str(self.lineEdit.text()).decode("utf-8")
    self.string=str(self.lineEdit_2.text()).decode("utf-8")
    file=open(self.name_file,"w")
    file.write(self.string)
    file.close()

When I enter English letters it works fine, but when I enter Arabic I get the following error:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)


回答1:


Instead of writing code to convert from your unicode to UTF-8, you wrote code to convert from UTF-8 to unicode. That's what you're getting errors.

decode("utf-8") means

Take a UTF-8 encoded binary str and convert to a unicode string.

Conversely, encode("utf-8") means

take a unicode string and encode into a binary str using UTF-8.

It looks like you're trying to encode text as UTF-8, so you can write it to your file in UTF-8 encoding. So you should use be using encode() instead of decode().

Also, you're taking your QString value, which is in unicode, and calling str() on it. This attempts to change it to a binary str using ASCII, which doesn't work for your Arabic text, and causes the exception you're seeing. And it's not what you wanted to do, anyway—you wanted to use UTF-8, not ASCII. So don't convert it to a binary str, convert it to a unicode object with unicode().

So, for example, instead of

str(self.lineEdit_2.text()).decode("utf-8")

you should write instead

unicode(self.lineEdit_2.text()).encode("utf-8")


来源:https://stackoverflow.com/questions/36220459/how-to-convert-arabic-text-from-pyqt4-to-utf-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!