文本预处理
文本是一类序列数据,一篇文章可以看作是字符或单词的序列,本节将介绍文本数据的常见预处理步骤,预处理通常包括四个步骤:
- 读入文本
- 分词
- 建立字典,将每个词映射到一个唯一的索引(index)
- 将文本从词的序列转换为索引的序列,方便输入模型
import collections
import re
def read_time_machine():
with open('/home/kesci/input/timemachine7163/timemachine.txt', 'r') as f:
lines = [re.sub('[^a-z]+', ' ', line.strip().lower()) for line in f]
return lines
#.strip()移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
#.lower()转换字符串中所有大写字符为小写。
#re.sub是个正则表达式替换函数,用来实现通过正则表达式,实现比普通字符串的replace更加强大的替换功能;
lines = read_time_machine()
print('# sentences %d' % len(lines))
#分词:我们对每个句子进行分词,也就是将一个句子划分成若干个词(token),转换为一个词的序列。
def tokenize(sentences, token='word'):
"""Split sentences into word or char tokens"""
if token == 'word':
return [sentence.split(' ') for sentence in sentences