1

我想将 Gtk.Clipboard.get() 返回值转换为 utf-8。

gtk3

from gi.repository import Gtk, Gdk

def main():
    clip = Gtk.Clipboard.get (Gdk.SELECTION_PRIMARY)
    text=clip.wait_for_text ()
    print text
    text=text.encode("utf-8")
    print text 

main()

它仅在所选文本仅保留 ascii 字符时才有效,但如果有一些国家字符(法语/德语等),我会从 text.encode(..) 函数中收到错误:UnicodeDecodeError: 'ascii' codec can't decode byte位置 1 中的 0xc3:序数不在范围内(128)

您知道问题出在哪里以及如何使 gtk3 版本正常工作吗?

当我使用 gtk2 的 gtk.clipboard_get() 函数时,这是正确的:

import gtk

def main():
    clip = gtk.clipboard_get ('PRIMARY')
    text=clip.wait_for_text ()
    print text
    text=text.encode("utf-8")
    print text 
main()

此致

4

2 回答 2

0

Just a guess here. The clipboard's wait_for_text() method, according to the documentation, is already supposed to give you UTF-8 encoded strings. It might be that the GTK 3 version is mistakenly returning a str instead of a unicode object. To test this, try adding

print type(text)

to see what kind of object it is.

You can try utext = text.decode('utf8') to get a unicode object.

于 2012-05-31T19:04:51.567 回答
0

wait_for_text()确实返回str类型,但这不是错误:utf-8 字符串由str类型表示。

我还想到这条线总是会产生错误:

some_Unicode_String_With_Non_Ascii.encode("utf-8").encode("utf-8"),

因此,我的 gtk3 示例行为正确。作为结论:text.encode("utf-8")应该删除操作。

于 2012-06-01T13:30:25.823 回答