问题
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
strand convert to aunicodestring.
Conversely, encode("utf-8") means
take a
unicodestring and encode into a binarystrusing 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