gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:47:05 25 4
gpt4 key购买 nike

我使用 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")

关于python - 如何将阿拉伯文本从 PyQt4 转换为 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36220459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com