4 文本预处理
4.1 简单的文本预处理步骤
文本是一类序列数据,一篇文章可以看作是字符或单词的序列,本节将介绍文本数据的常见预处理步骤,预处理通常包括四个步骤:
(1)读入文本
(2)分词
(3)建立字典,将每个词映射到一个唯一的索引(index)
(4)将文本从词的序列转换为索引的序列,方便输入模型
4.2 pytorch实现
(1)读入文本
# 读入文本
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
lines = read_time_machine()
print('# sentences %d' % len(lines))
(2)分词
# 分词 返回结果为二维列表
def tokenize(sentences, token='word'):
"""Split sentences into word or char tokens"""
if token == 'word':
return [sentence.split(' ') for sentence in sentences]
elif token == 'char':
return [list(sentence) for sentence in sentences]
else:
print('ERROR: unkown token type '+token)
tokens = tokenize(lines)
tokens[0:2]
(3)建立字典,将每个词映射到一个唯一的索引(index)
# 建立字典
# tokens相当于tokenize的结果,即一个二维数据,为整个语料库中的词
# min_freq:词频的阈值,如果某个词出现的频率小于阈值,则可以直接忽视这个词
# tokens:
# pad: 在小批量中数据不等长时做填充