将unicode字符打印为字符串

2024-10-04 05:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我用pynput得到tyoed字符,然后我想将其重新键入为字符串,例如“č”为“č”,而不是u'\u010d' 我做错什么了?在

# -*- coding: utf-8 -*-
from pynput import keyboard

def on_press(key):
    try:
        moje = format(key.char)
    except AttributeError:
        print('special key {0} pressed'.format(key))

def on_release(key):
    #print('{0} released'.format(key).encode('utf-8'))
    #print('{0} released'.format(key).encode('cp437'))
    a = format(key)
    a = a.encode('cp437')
    print a #<-- here are "bad" chars produced / especially decoding issues / it shows unicode string but I am not able to show it properly, or save it to file, it shows/saves u'\u010d' instead of č
#     import codecs
#     f = codecs.open("test", "w", "utf-8-sig")
#     #f = open('test', 'w')
#     f.write(a) #<-- here are "bad" chars produced / especially decoding issues / it shows unicode string but I am not able to show it properly, or save it to file, it shows/saves u'\u010d' instead of č
#     f.close()
#     f = file('test', 'r')
#     print f.read().decode('cp437')
#     print u'\u0420\u043e\u0441\u0441\u0438\u044f'
    #print  u'não vou esqueçer mais de usar o u no começo' 
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# Collect events until they are released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

Tags: tokeyformatreleaseonitutfshows