gpt4 book ai didi

Python 脚本不适用于 Autokey

转载 作者:可可西里 更新时间:2023-11-01 11:49:52 26 4
gpt4 key购买 nike

我正在尝试在 Python 上制作一个 html 实体编码器/解码器,其行为类似于 PHP 的 htmlentitieshtml_entity_decode,它作为独立脚本正常工作:

我的输入:

Lorem ÁÉÍÓÚÇÃOÁáéíóúção @#$%*()[]<>+ 0123456789

python解码.py

输出:

Lorem ÁÉÍÓÚÇÃOÁáéíóúção @#$%*()[]<>+ 0123456789

现在,如果我将它作为 Autokey 脚本运行,我会收到此错误:

Script name: 'html_entity_decode'
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/autokey/service.py", line 454, in execute
exec script.code in scope
File "<string>", line 40, in <module>
File "/usr/local/lib/python2.7/dist-packages/autokey/scripting.py", line 42, in send_keys
self.mediator.send_string(keyString.decode("utf-8"))
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-12: ordinal not in range(128)

我做错了什么?这是脚本:

import htmlentitydefs
import re

entity_re = re.compile(r'&(%s|#(\d{1,5}|[xX]([\da-fA-F]{1,4})));' % '|'.join(
htmlentitydefs.name2codepoint.keys()))

def html_entity_decode(s, encoding='utf-8'):

if not isinstance(s, basestring):
raise TypeError('argument 1: expected string, %s found' \
% s.__class__.__name__)

def entity_2_unichr(matchobj):
g1, g2, g3 = matchobj.groups()
if g3 is not None:
codepoint = int(g3, 16)
elif g2 is not None:
codepoint = int(g2)
else:
codepoint = htmlentitydefs.name2codepoint[g1]
return unichr(codepoint)

if isinstance(s, unicode):
entity_2_chr = entity_2_unichr
else:
entity_2_chr = lambda o: entity_2_unichr(o).encode(encoding,
'xmlcharrefreplace')
def silent_entity_replace(matchobj):
try:
return entity_2_chr(matchobj)
except ValueError:
return matchobj.group(0)

return entity_re.sub(silent_entity_replace, s)

text = clipboard.get_selection()
text = html_entity_decode(text)
keyboard.send_keys("%s" % text)

我在 Gist https://gist.github.com/607454 上找到它,我不是作者。

最佳答案

查看回溯,可能的问题是您将 unicode 字符串传递给 keyboard.send_keys,它需要 UTF-8 编码的字节串。 autokey 然后尝试解码失败的字符串,因为输入是 unicode 而不是 utf-8。这看起来像是 autokey 中的一个错误:它不应该尝试解码字符串,除非它们真的是纯(字节)字符串。

如果这个猜测是正确的,你应该能够通过确保将 unicode 实例传递给 send_keys 来解决这个问题。尝试这样的事情:

text = clipboard.get_selection()
if isinstance(text, unicode):
text = text.encode('utf-8')
text = html_entity_decode(text)
assert isinstance(text, str)
keyboard.send_keys(text)

断言不是必需的,但它是一种方便的健全性检查,以确保 html_entity_decode 做正确的事情。

关于Python 脚本不适用于 Autokey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14145008/

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