- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我使用 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 aunicode
string.
相反,encode("utf-8")
表示
take a
unicode
string and encode into a binarystr
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/
我是一名优秀的程序员,十分优秀!