Python str.translate unicode

时间:2018-09-02 19:30:42

标签: python unicode translation python-2.x

所以我正在创建一个python键盘记录器。我设法在按下某个键时获得了differnet修饰符的键状态,因此我开发了一个函数,例如在按下shift键时将大写字母放入大写字母,这里是:

def applyKeyModifier(x,shift,ctrl,altgr,win):
    keyboard      = u"""²&é"'(-è_çà)=azertyuiop^$qsdfghjklmù*<wxcvbn,;:!/*-+"""
    shiftModified = u"""_1234567890°+AZERTYUIOP¨£QSDFGHJKLM%µ>WXCVBN?./§/*-+"""
    altgrModified = u"""__~#{[|`\^@]}€__________¤___________________________"""

    shiftTranslation = string.maketrans(keyboard, shiftModified)
    altgrTranslation = string.maketrans(keyboard, altgrModified)
    if shift and not altgr and not ctrl and not win:
        translated = x.translate(shiftTranslation)
        if translated == "_":
            translated=""
        return translated
    elif altgr and not shift and not ctrl and not win:
        translated = x.translate(shiftTranslation)
        if translated == "_":
            translated=""
        return translated
    elif ctrl and not shift and not altgr and not win: 
        return " [CTRL+"+x+"] "
    elif win and not shift and not altgr and not ctrl: 
        return " [WIN/CMD+"+x+"] "
    else:
        return x

唯一的问题是我收到此错误:

C:\Users\tugle\Desktop>python keylogger.py
Traceback (most recent call last):
  File "keylogger.py", line 139, in <module>
    listener.join()
  File "C:\dev\Python27\lib\site-packages\pynput\_util\__init__.py", line 199, in join
    six.reraise(exc_type, exc_value, exc_traceback)
  File "C:\dev\Python27\lib\site-packages\pynput\_util\__init__.py", line 154, in inner
    return f(self, *args, **kwargs)
  File "C:\dev\Python27\lib\site-packages\pynput\keyboard\_win32.py", line 237, in _process
    self.on_press(key)
  File "C:\dev\Python27\lib\site-packages\pynput\_util\__init__.py", line 75, in inner
    if f(*args) is False:
  File "keylogger.py", line 117, in on_press
    keybuffer += applyKeyModifier(str(key),isShift,isCtrl,isAltGr,isWin)
  File "keylogger.py", line 19, in applyKeyModifier
    shiftTranslation = string.maketrans(keyboard, shiftModified)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb2' in position 0: ordinal not in range(128)

我正在使用python2。所以有人可以在这里帮助我

1 个答案:

答案 0 :(得分:1)

translate()方法的行为有所不同,具体取决于是在str还是unicode上调用它。您正在使用非ASCII字符,因此您的字符串应为unicode对象,并且unicode.translate()采用映射(dict)而不是maketrans表。 Quoth the docs:

  

对于Unicode对象,translate()方法不接受可选的 deletechars 参数。而是,它返回 s 的副本,在该副本中,所有字符都已通过给定的转换表进行映射,该表必须是Unicode常规到Unicode常规,Unicode字符串或None的映射。未映射的字符保持不变。映射到None的字符将被删除。

因此,shiftTranslation的格式应为:

shiftTranslation = {
    ord(u'²'): u'_',
    ord(u'&'): u'1',
    ord(u'é'): u'2',
    # etc.
}