检查可打印的Unicode

Cos*_*Inc 1 python unicode

我知道要检查字符串是否可打印,我们可以执行以下操作:

def isprintable(s,codec='utf8'):
    try: 
        s.codec(codec)
    except UnicodeDecodeError: 
        return False
    else: 
        return True
Run Code Online (Sandbox Code Playgroud)

但有没有办法用Unicode,而不是字符串?顺便说一句,我正在使用推文,我将推文转换为Unicode,如下所示

text=unicode(status.text)
Run Code Online (Sandbox Code Playgroud)

boo*_*chk 10

我不确定使用代码点的解决方案在面对Unicode标准更改或不同编码时是否可靠.更抽象的解决方案:

import unicodedata

if unicodedata.category(char) == 'Cc':
        raise UnhandledKeypressError('unprintable char')
Run Code Online (Sandbox Code Playgroud)

换句话说,如果字符串的所有字符(unicode对象)都没有具有值"control"的属性类别,则该字符串是可打印的.

为了比较,Qt的QChar.isPrint():

如果字符是可打印字符,则返回true; 否则返回false.这是任何不属于Cc或Cn类别的角色.请注意,这不表示该字符是否以特定字体可用.