字符串与文本04-正则中用Unicode / 删除字符串中的空格 / 审查清理文本字符串

正则式中使用 Unicode


  • re 模块 \\d

默认情况下 re 模块已经对一些 Unicode 字符类有了基本的支持。比如, \d 已经匹配任意的 unicode 数字字符

import re
num = re.compile('\d+') 

print(num.match('123'))      #<_sre.SRE_Match object; span=(0, 3), match='123'>
print(num.match('\u0661\u0662\u0663'))     #<_sre.SRE_Match object; span=(0, 3), match='١٢٣'>

如果你想在模式中包含指定的 Unicode 字符,你可以使用 Unicode 字符对应的转义序列 (比如 \uFFF 或者 \UFFFFFFF )。比如,下面是一个匹配几个不同阿拉伯编码页面中所有字符的正则表达式:

arabic = re.compile('[\u0600-\u06ff\u0750-\u077f\u08a0-\u08ff]+')

当执行匹配和搜索操作的时候,最好是先标准化并且清理所有文本为标准化格式。但是同样也应该注意一些特殊情况,比如在忽略大小写匹配和大小写转换时的行为

import re

pat = re.compile('stra\u00dfe', re.IGNORECASE)
s = 'straße'
print(pat.match(s))   # <_sre.SRE_Match object; span=(0, 6), match='straße'>

print(pat.match(s.upper()))    # None
print(s.upper())    # STRASSE

删除字符串中不需要的字符

想去掉文本字符串开头,结尾或者中间不想要的字符,比如空白?
- 用 strip()删除头尾空白
此法用于删除开始或结尾的字符。

#使用strip()删除开始和结尾的空格符
s = ' hello world \n'
print(s.strip())       # hello world


  • lstrip() 和 rstrip()定义删除头或尾

lstrip() 和 rstrip() 分别是从左和从右执行删除操作。默认情况下,这些方法会去除空格符,但是也可以指定其他字符。

s = '  fuck you    \n'
#删除左边的空格
print(s.lstrip())    # 'fuck you    '
#删除右边的空格
print(s.rstrip())    #'  fuck you'

t = '-----hello====='
#自定义删除左边的‘-’
print(t.lstrip('-'))    # 'hello====='
#删除两边的‘-=’
print(t.strip('-='))    # 'hello'


  • 用 replace()删除中间

去除操作不会对字符串的中间的空格符产生任何影响。想去除中间的空格,就要用到 replace()
s = 'are you talking to me?'
print(s.replace(' ', ''))     # areyoutalkingtome?
  • 或使用正则 re 删中间空格
s = 'are you talking to me?'

import re
print(re.sub('\s+', '', s))  # areyoutalkingtome?

审查清理文本字符串

  • 'pýtĥöñ\fis\tawesome\r\n'
s = 'pýtĥöñ\fis\tawesome\r\n'
print(s)   #  pýtĥöñis awesome

#清理第一步:替换(把另一奇怪的字符先换成空格符)
p = {
    ord('\t') : ' ',
    ord('\f') : ' ',
    ord('\r') : None # Deleted
}
afterTranslate = s.translate(p)
print(afterTranslate)    # pýtĥöñ is awesome

#第二步,分解形式字符。
import unicodedata

#使用多组合的标准化方式NFD,分离出和音符
b = unicodedata.normalize('NFD', afterTranslate)
print(b)   #pýtĥöñ is awesome

#第三步,删除和音符
'''方法一'''
print(b.encode('ascii', 'ignore').decode('ascii'))  # python is awesome

'''方法二'''
import sys

#使用 dict.fromkeys() 方法构造一个字典,每个 Unicode 和音符作为键,对于的值全部为 None
Nonedict = dict.fromkeys(c for c in range(sys.maxunicode)if unicodedata.combining(chr(c)))
#调用 translate 函数删除所有重音符。
print(b.translate(Nonedict))   # python is awesome

第三步方法一涉及到 I/O 解码与编码函数。这里的思路是先对文本做一些初步的清理,然后再结合 encode() 或者 decode() 操作来清除或修改它。
而方法二中,通过使用 dict.fromkeys() 方法构造一个字典,每个 Unicode 和音符作为键,对于的值全部为 None 。然后使用 unicodedata.normalize() 将原始输入标准化为分解形式字符。然后再调用 translate 函数删除所有重音符。

猜你喜欢

转载自blog.csdn.net/xiangchi7/article/details/82433233
今日推荐