文本预处理的核心思想是如何将文本中转化成能够训练的样本,而且通常情况下是转化成序列数据。通常有以下几个步骤:
通常英文和中文的处理会有些差别,我们分别举例讲解
处理英文文本
- 加载原始文本(一般我们按行来进行处理,因此一行一行的读)
import collections
import re
from d2l import torch as d2l
# 这里主要是懒得再去下载英文文章了,就直接copy的李沐老师的代码
d2l.DATA_HUB['time_machine'] = (d2l.DATA_URL + 'timemachine.txt',
'090b5e7e70c295757f55df93cb0a180b9691891a')
def read_time_machine():
"""将时间机器数据集加载到文本行的列表中"""
with open(d2l.download('time_machine'), 'r') as f:
lines = f.readlines()
return [re.sub('[^A-Za-z]+', ' ', line).strip().lower() for line in lines]
# 这一步是暴力将所有非英文字符全部替换并转换成小写
# 可能会有一些问题,但是无伤大雅
lines = read_time_machine()
print(lines[0])
print(lines[10])
the time machine by h g wells
twinkled and his usually pale face was flushed and animated the
- 获得每一行句子的token(可以理解为词汇表)
# 这里由于是英文,都是空格分割,相对好处理,中英文的处理差别就在这儿
def tokenize(lines, token='word'):
"""将文本行拆分为单词或字符词元"""
if token == 'word':
return [line.split() for line in lines]
elif token == 'char':
return [list(line) for line in lines]
else:
print('错误:未知词元类型:' + token)
tokens = tokenize(lines)
for i in range(11):
print(tokens[i])
['the', 'time', 'machine', 'by', 'h', 'g', 'wells']
[]
[]
[]
[]
['i']
[]
[]
['the', 'time', 'traveller', 'for', 'so', 'it', 'will', 'be', 'convenient', 'to', 'speak', 'of', 'him']
['was', 'expounding', 'a', 'recondite', 'matt