unicodedata.normalize()/使用strip()、rstrip()和lstrip()/encode和decode 笔记(具体可看 《Python Cookbook》3rd Edition 2.9~2.11)

unicodedata.normalize()清理字符串

# normalize()的第一个参数指定字符串标准化的方式,分别有NFD/NFC

>>> s1 = 'Spicy Jalapeu00f1o'
>>> s2 = 'Spicy Jalapenu0303o'
>>> import unicodedata
# NFC表示字符应该是整体组成(可能是使用单一编码)
>>> t1 = unicodedata.normalize('NFC', s1)
>>> t2 = unicodedata.normalize('NFC', s2)
>>> t1 == t2
True
# NFD表示字符应该分解为多个组合字符表示
>>> t1 = unicodedata.normalize('NFD', s1)
>>> t2 = unicodedata.normalize('NFD', s2)
>>> t1 == t2
True

注:Python中同样支持NFKC/NFKD,使用原理同上


combining()匹配文本上的和音字符

>>> s1
'Spicy Jalapeño'
>>> t1 = unicodedata.normalize('NFD', s1)
>>> ''.join(c for c in t1 if not unicodedata.combining(c)) # 去除和音字符
'Spicy Jalapeno'

使用strip()、rstrip()和lstrip()

>>> s = ' hello world 
'
# 去除左右空白字符
>>> s.strip()
'hello world'
# 去除右边空白字符
>>> s.rstrip()
' hello world'
# 去除左边空白字符
>>> s.lstrip()
'hello world 
'
>>> t = '-----hello====='
# 去除左边指定字段('-')
>>> t.lstrip('-')
'hello====='
# 去除右边指定字段('-')
>>> t.rstrip('=')
'-----hello'

# 值得注意的是,strip等不能够去除中间空白字符,要使用去除中间空白字符可以使用下面方法

>>> s = ' hello world 
'
# 使用replace()那么会造成"一个不留"
>>> s.replace(' ', '')
'helloworld
'
# 使用正则
>>> import re
>>> re.sub(r's+', ' ', s)
' hello world '

关于translate()

# 处理和音字符

>>> s = 'pýtĥöñfis	awesome
'
>>> remap = {ord('
'): None, ord('	'): ' ', ord('f'): ' '} # 构造字典,对应空字符
>>> a = s.translate(remap) # 进行字典转换
>>> a
'pýtĥöñ is awesome
'
>>> import unicodedata
>>> import sys
>>> cmb_chrs = dict.fromkeys(c for c in range(sys.maxunicode) if unicodedata.combining(chr(c))) # 查找系统的和音字符,并将其设置为字典的键,值设置为空
>>> b = unicodedata.normalize('NFD', a) # 将原始输入标准化为分解形式字符
>>> b
'pýtĥöñ is awesome
'
>>> b.translate(cmb_chrs)
'python is awesome
'

# 将所有的Unicode数字字符映射到对应的ASCII字符上

# unicodedata.digit(chr(c)) # 将ASCII转换为十进制数字,再加上'0'的ASCII就对应了“0~9”的ASCII码
>>> digitmap = {c: ord('0')+unicodedata.digit(chr(c)) for c in range(sys.maxunicode) if unicodedata.category(chr(c)) == 'Nd'} # (unicodedata.category(chr(c)) == 'Nd')表示系统“0~9”的Unicode字符
>>> len(digitmap)
610
>>> x = 'u0661u0662u0663'
>>> x.translate(digitmap)
'123'

关于I/O解码和编码函数

>>> a
'pýtĥöñ is awesome
'
>>> b = unicodedata.normalize('NFD', a)
>>> b.encode('ascii', 'ignore').decode('ascii')
'python is awesome
'
原文地址:https://www.cnblogs.com/namejr/p/9985382.html