这里主要讲解下英语词语处理的过程。(参考伯禹教育课程)
- 读入文本
- 分词
- 建立字典,将每个词映射到一个唯一的索引(index)
- 将文本从词的序列转换为索引的序列,方便输入模型
根据停用词 词频 TF-IDF等方法计算每个英文的词频。然后建立词语与索引的映射。
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))
re()正则函数 在这里re.sub('[^a-z]时把除a-z的其他字符都换成 空格 这是最简单的方法
分词
我们对每个句子进行分词,也就是将一个句子划分成若干个词(token),转换为一个词的序列。
In [2]:
def tokenize(sentences, token='word'): """Split sentences into word or char tokens""" if token == 'word': return [sentence.split(' ') for sentence