curses.getch 中的西里尔字符编码错误

问题描述 投票:0回答:1

我正在编写一个消息程序,我需要一个带有一些高级功能的文本框。

我见过一个curses.textpad,但它不符合我的需求。

好吧,如果我输入西里尔字符,getch() 返回错误的字符,例如

Ð¿Ñ Ð²ÐивеÑ

import curses

class inputbox:
    def get():
        win = curses.newwin(3, 35, 4, 4)
        win.keypad(True)
        inp = True
        text = ""

        while inp:
            ch = win.getch()

            if ch == 10:
                text += "\n"
                inp = False
            if ch == 263 or ch == curses.KEY_BACKSPACE:
                text = text[:len(text)-1]
                currpos = win.getyx()
                win.addstr(currpos[0], currpos[1], " ")
                win.move(currpos[0], currpos[1])
            else:
                text += chr(ch)
            win.refresh()

        return text


def main(stdscr):
    curses.echo()
    inp = inputbox()
    text = inputbox.get()

    stdscr.addstr(0, 0, text)
    stdscr.getstr()

if __name__ == "__main__":
    curses.wrapper(main)
python python-3.x unicode curses cyrillic
1个回答
0
投票

由于西里尔文在 unicode 中用两个字节表示,因此您可以单独处理当您收到非 ASCII 第一个字节(西里尔文为 208 或 209),然后立即读取第二个字节时的情况

然后可以从 unicode 解码两个字节的字符串,将其附加到文本中

ch = win.getch()
    if ch == 208 or ch == 209:
        second_ch = win.getch()
        text += (ch.to_bytes() + second_ch.to_bytes()).decode('utf-8')
        continue
© www.soinside.com 2019 - 2024. All rights reserved.