如何将阿拉伯文本从 PyQt4 转换为 UTF-8

How to convert Arabic text from PyQt4 to UTF-8

我用 PyQt4 制作了一个 Python 2 GUI 应用程序,它有两个条目。第一个取文件名,第二个取要写入文件的文本。

两个都想输入阿拉伯文字,所以写了这个函数:

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()

当我输入英文字母时,它工作正常,但当我输入阿拉伯语时,出现以下错误:

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

您没有编写将 unicode 转换为 UTF-8 的代码,而是编写了将 UTF-8 转换为 unicode 的代码。这就是你遇到的错误。

decode("utf-8")表示

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

反之,encode("utf-8")表示

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

您似乎正在尝试将文本编码为 UTF-8,因此您可以使用 UTF-8 编码将其写入您的文件。所以你应该使用 encode() 而不是 decode().

此外,您正在使用 unicode 格式的 QString 值,并对其调用 str()。这会尝试使用 ASCII 将其更改为二进制 str,这不适用于您的阿拉伯语文本,并导致您看到的异常。无论如何,这不是您想要做的 — 您想要使用 UTF-8,而不是 ASCII。所以不要将其转换为二进制str,将其转换为具有unicode().

unicode对象

所以,例如,而不是

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

你应该改写

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