preface:随着经历的积累,觉得预处理问题愈发重要,需要整理整理。
环境:mac,anaconda2
目录
一、文本编码转换
- python2 VS python3
- python2读取文件:默认asciii,类型为str
- 转为utf-8 demo:
-
$ ipython # 改变默认编码格式为utf-8 import sys reload(sys) sys.setdefaultencoding('utf-8') s = '今天上海的天气也蛮不错的' us = unicode(s) print type(s), len(s), s print type(us), len(us), us s us ''' # 结果 <type 'str'> 36 今天上海的天气也蛮不错的 <type 'unicode'> 12 今天上海的天气也蛮不错的 '\xe4\xbb\x8a\xe5\xa4\xa9\xe4\xb8\x8a\xe6\xb5\xb7\xe7\x9a\x84\xe5\xa4\xa9\xe6\xb0\x94\xe4\xb9\x9f\xe8\x9b\xae\xe4\xb8\x8d\xe9\x94\x99\xe7\x9a\x84' u'\u4eca\u5929\u4e0a\u6d77\u7684\u5929\u6c14\u4e5f\u86ee\u4e0d\u9519\u7684' '''
-
- 转为utf-8 demo:
- python3:
- 中文字符串转为unicode:Chinesename.encode('unicode_escape').参考:https://blog.csdn.net/xyq046463/article/details/58606657
- 默认utf-8格式,并且显示为str类型,不必转换格式,这一块比较好
- unicode转为byte格式:s.encode()
- byte格式转为unicode:s.decode()
- 使用例子1:在做tensorflow的tfrecord时,需要将输入文本转为Byte格式,传入BytesList
-
# python3环境下准备tfrecord时 values = [sentence.encode("utf-8") for sentence in doc] record = {'text_feature_keys':tf.train.Feature(bytes_list=tf.train.BytesList(value=values)),}
-
- 例子:
-
$ /anaconda3/bin/ipython s = '今天上海的天气也蛮不错的' bs = s.endcode() print('{},{},{}'.format(type(s),len(s),s)) print('{},{},{}'.format(type(bs),len(bs),bs)) ''' # 结果 <class 'str'>,12,今天上海的天气也蛮不错的 <class 'bytes'>,36,b'\xe4\xbb\x8a\xe5\xa4\xa9\xe4\xb8\x8a\xe6\xb5\xb7\xe7\x9a\x84\xe5\xa4\xa9\xe6\xb0\x94\xe4\xb9\x9f\xe8\x9b\xae\xe4\xb8\x8d\xe9\x94\x99\xe7\x9a\x84' '''
-
- python2读取文件:默认asciii,类型为str
- python2中需要注意的坑:详见以前的博客,python函数——编码问题——str与Unicode的区别
- 编码这块还是建议大家用python3,python2在2020年后就不支持了,python2中的编码实在太多坑了。
二、繁转简
- 背景:无论微博文本、点评评论文本、豆瓣影评文本,都有繁体的存在,繁体占比比较少但又不可不考虑,这样就导致训练时繁体的语义不能用上汉字的语义了,毕竟繁体字在计算机中也单独被认为一个汉字,如若不预处理的话。
- 坑:存在坑爹的栗子。(长度会改变,并且差了很多)
- 泡麵——>方便面
- 雪糕——>冰淇淋
- 繁转简方法1(慢)
- 下载到本地的备用文件:zh_wiki.py、langconv.py
- 使用:
-
from langconv import * keyword = '飛機飛向藍天' keyword = Converter("zh-hans").convert(keyword.decode("utf-8")).encode("utf-8") #繁体转简体 keyword = Converter("zh-hant").convert(keyword.decode("utf-8")).encode("utf-8") #简体转繁体
-
- 参考:python实现中文字符繁体和简体中文转换
- 缺点:较慢,针对每个词,都要过一遍繁体字典,卤煮处理上百万条评论时,加了一个繁转简,预处理时间瞬间拉长了好几分钟。
- 繁转简方法2(快)
- 使用snownlp包自带的繁转简,demo:
-
$ pip install SnowNLP $ ipython from snownlp import SnowNLP s = SnowNLP(u'「繁體字」「繁體中文」的叫法在臺灣亦很常見。') print s.h
-
- 使用snownlp包自带的繁转简,demo: