我知道要检查一个字符串是否可打印,我们可以这样做:
def isprintable(s,codec='utf8'):
try:
s.codec(codec)
except UnicodeDecodeError:
return False
else:
return True
但是有没有办法用 Unicode 而不是字符串来做到这一点? 顺便说一句,我正在处理推文,我按如下方式将推文转换为 Unicode
text=unicode(status.text)
请您参考如下方法:
面对 Unicode 标准更改或不同编码,我不确定使用代码点的解决方案是否可靠。更抽象的解决方案:
import unicodedata
if unicodedata.category(char) == 'Cc':
raise UnhandledKeypressError('unprintable char')
换句话说,如果一个字符串的所有字符(unicode 对象)都不具有值为“control”的属性类别,则该字符串是可打印的。
为了比较,Qt 的 QChar.isPrint() :
Returns true if the character is a printable character; otherwise returns false. This is any character not of category Cc or Cn. Note that this gives no indication of whether the character is available in a particular font.
