动手学深度学习——文本预处理
文本预处理 文本预处理是NLP中不可或缺的一项任务。文本预处理通常包括四个步骤:读入文本、分词、建立字典、将文本从词序列转换为索引序列。 (1)读入文本 import collections import re def read_time_machine(): with open('/home/kesci/input/timemachine7163/timemachine.txt', 'r') as f: #以读的方式打开文本,并重新命名为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