gpt4 book ai didi

python - 如何识别Python中不可打印的unicode字符

转载 作者:太空宇宙 更新时间:2023-11-03 15:45:55 37 4
gpt4 key购买 nike

我正在尝试使用随机字符生成 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 ])

来源:https://gist.github.com/Jonty/6705090

关于python - 如何识别Python中不可打印的unicode字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41757886/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com