标签 unicodedata 下的文章

文本预处理

过滤符号,去掉上标,转换为小写,非英文字符用空格隔开,连续重复字母数大于等于3的只保留1个,去掉指定单词中的空格。

import regex as re
import unicodedata
def process(text):
    try:
        text = re.sub(ur"\p{P}+|\p{Z}+|\p{S}+|\p{N}+", u' ', text)
        text = unicodedata.normalize('NFKD',text)#.encode('ascii','ignore')
        text = re.sub(ur"\p{M}+", u'', text)
        text = re.sub(ur"\p{P}+|\p{S}+|\p{N}+|\p{Cs}+|\p{Cf}+|\p{Co}+", u'', text)
        text = re.sub("([A-Za-z]+)", lambda m:m.group(1).lower(),text)
        text = re.sub(ur'([^\x00-\x7f])', lambda m:u' '+m.group(1)+u' ', text)
        text = re.sub(ur"(\w)\1{2,}",lambda m:m.group(1), text)
        text = re.sub("(\s+)", u' ',text)
        for fword in fword_list:
            f_re = ''
            for i in xrange(len(fword)):
                w = fword[i]
                f_re += w + "+\s*" if i < (len(fword)-1) else w + "+" 
            text = re.sub(f_re, u' '+fword+u' ',text)
        text = re.sub("(\s+)", u' ',text)
        return text
    except: 
        return text
df['text'] = df['text'].apply(lambda x: process(x))


使用unicodedata和regex将文本中的组合字符拆分

文本处理时有时候需要将组合字符对应到同一个字符,不同种类的组合字符拆分的结果会有区别,这里的组合字符以法语字符举例。

代码示例如下:

import regex as re
import unicodedata
text = u'à ? ? è é ê ? ? ? ? ù ? ? ?'
print (text)
text = unicodedata.normalize('NFD',text)
print (text)
text = re.sub(ur'\p{M}',u'',text)
print (text)

输出结果为:

à ? ? è é ê ? ? ? ? ù ? ? ?
a? a? c? e? e? e? e? i? i? o? u? u? ? C?
a a c e e e e i i o u u ? C

其中的NFD可以换成NFKD,在当前情况下结果相同,在控制台中的输出和这里显示的有些不一样。

unicodedata.png

第二行中的数据被拆分为:

u'a\u0300 a\u0302 c\u0327 e\u0300 e\u0301 e\u0302 e\u0308 i\u0302 i\u0308 o\u0302 u\u0300 u\u0302 \u0153 C\u0327'