[英]How can I recognise Non printable unicode characters in python
我正在嘗試使用隨機字符生成 Unicode 字符串。 我不想在字符串中有不可打印的字符。 使用 'unichr(codepoint)' 函數我正在將代碼點轉換為 Unicode 並使用 'unicode.encode('utf-8')' 我正在將 Unicode 轉換為字符串。 我嘗試使用 string.printable 但這僅涵蓋 ASCII。
您可以使用unicodedata
庫。
import unicodedata
def strip_string(self, string):
"""Cleans a string based on a whitelist of printable unicode categories
You can find a full list of categories here:
http://www.fileformat.info/info/unicode/category/index.htm
"""
letters = ('LC', 'Ll', 'Lm', 'Lo', 'Lt', 'Lu')
numbers = ('Nd', 'Nl', 'No')
marks = ('Mc', 'Me', 'Mn')
punctuation = ('Pc', 'Pd', 'Pe', 'Pf', 'Pi', 'Po', 'Ps')
symbol = ('Sc', 'Sk', 'Sm', 'So')
space = ('Zs',)
allowed_categories = letters + numbers + marks + punctuation + symbol + space
return u''.join([ c for c in string if unicodedata.category(c) in allowed_categories ])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.