26 lines
1.0 KiB
Python
26 lines
1.0 KiB
Python
import sys
|
||
|
||
import unicodedata
|
||
|
||
if __name__ == '__main__':
|
||
# 总有脑瘫喜欢输入一些奇奇怪怪的东西,这个时候我们就需要做一些过滤操作
|
||
s = 'pyth\u0303on\fis\tawesome\r\n'
|
||
# 这个字符串看起来就非常恶心了,这时候我们可以用translate方法对一些特殊符号进行迭代:
|
||
remap = {
|
||
ord('\t'): ' ',
|
||
ord('\f'): ' ',
|
||
ord('\r'): None,
|
||
}
|
||
s = s.translate(remap)
|
||
print(s)
|
||
|
||
# 这个时候我们就过滤掉了各种空格符和回车符
|
||
# 我们也可以构建更大的order_dict去把unicode过滤掉
|
||
b = unicodedata.normalize("NFD", s)
|
||
# 对每一个unicode建立一个None的映射,
|
||
cmb_dict = dict.fromkeys(c for c in range(sys.maxunicode) if unicodedata.combining(chr(c)))
|
||
b = b.translate(cmb_dict)
|
||
print(b)
|
||
|
||
# 如果只是简单的替换操作,那么replace函数已经很好了,速度也很快;
|
||
# 在做字符映射操作的时候可以使用translate方法并构建一个映射字典 |