Files
Python_CookBook_repo/2.字符串和文本/12.文本过滤和清理.py
2025-09-10 16:12:45 +08:00

26 lines
1.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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方法并构建一个映射字典