文本预处理
import collections
import re
from d2l import torch as d2l
读取数据集
#@save
d2l.DATA_HUB['time_machine'] = (d2l.DATA_URL + 'timemachine.txt',
'090b5e7e70c295757f55df93cb0a180b9691891a')
def read_time_machine(): #@save
"""将时间机器数据集加载到文本行的列表中"""
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(f'# 文本总行数: {len(lines)}')
print(lines[0])
print(lines[10])
下载的’time_machine’是一本科幻小说.txt
re.sub('[^A-Za-z]+', ' ', line)
把只保留文本中的英文字母大小写,其他全部换成空格
strip()
去掉句首和句尾的空格,lower()
在转换为小写
输出
Downloading D:\environment\data\data\timemachine.txt from http://d2l-data.s3-accelerate.amazonaws.com/timemachine.txt...
# 文本总行数: 3221
the time machine by h g wells
twinkled and his usually pale face was flushed and animated the
现在我们得到了一行一行的文本
词元化
def tokenize(lines, token='word'): #@save
"""将文本行拆分为单词或字符词元"""
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])
将一行一行的文本作为输入,把他们切成token(词元)
word:把词当成token
char:把字符当作token,在这里就只有27个,但后续字符如何构成单词也变成了要学习的内容,list()字符串转换成列表:按字符分开了
返回的tokens是一个列表套列表
[[...] [...] [...] [...]]
['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', 'matter', 'to', 'us', 'his', 'grey', 'eyes', 'shone', 'and']
['twinkled', 'and', 'his', 'usually', 'pale', 'face', 'was', 'flushed', 'and', 'animated', 'the']
中文的话,如果想用词来表示一个token就要用到分词
构建词表
把token放进词汇表,有索引,因为我最后输入都是向量,里面放的都是索引
class Vocab: #@save
"""文本词表"""
def __init__(self, tokens=None, min_freq=0, reserved_tokens=None):
if tokens is None:
tokens = []
if reserved_tokens is None:
reserved_tokens = []
# 按出现频率排序
counter = count_corpus(tokens)
# 排序,出现次数从大到小
self._token_freqs = sorted(counter.items(), key=lambda x: x[1],
reverse=True)
# 未知词元的索引为0
self.idx_to_token = ['<unk>'] + reserved_tokens
self.token_to_idx = {token: idx
for idx, token in enumerate(self.idx_to_token)}
for token, freq in self._token_freqs:
if freq < min_freq:
break
if token not in self.token_to_idx:
self.idx_to_token.append(token)
self.token_to_idx[token] = len(self.idx_to_token) - 1
def __len__(self):
return len(self.idx_to_token)
def __getitem__(self, tokens):
if not isinstance(tokens, (list, tuple)):
return self.token_to_idx.get(tokens, self.unk)
return [self.__getitem__(token) for token in tokens]
def to_tokens(self, indices):
if not isinstance(indices, (list, tuple)):
return self.idx_to_token[indices]
return [self.idx_to_token[index] for index in indices]
@property
def unk(self): # 未知词元的索引为0
return 0
@property
def token_freqs(self):
return self._token_freqs
def count_corpus(tokens): #@save
"""统计词元的频率"""
# 这里的tokens是1D列表或2D列表
if len(tokens) == 0 or isinstance(tokens[0], list):
# 将词元列表展平成一个列表
tokens = [token for line in tokens for token in line]
return collections.Counter(tokens)
def __init__(self, tokens=None, min_freq=0, reserved_tokens=None):
min_freq:一个token能够被放进词表中需要出现的最少次数
reserved_tokens:一个token是句子的开始还是结束,目前还用不到
count_corpus(tokens):
返回一个词典Counter({'the': 2261, 'time': 200, 'machine': 85, 'by': 103, 'h': 1, 'g': 1, 'wells': 9, 'i': 1267, 'traveller': 61, 'for': 221, 'so': 112, 'tableful': 1, 'amazing': 2, 'plight': 1, ...})
sorted(counter.items(), key=lambda x: x[1], reverse=True):
counter.items():一个可迭代对象
key=lambda x: x[1]:隐函数,用来进行比较的元素,x[1]就是出现的次数
reverse=True:降序
__getitem__(self, tokens):
给索引,返回token
def to_tokens(self, indices):
给token,返回索引
试试看
vocab = Vocab(tokens)
print(list(vocab.token_to_idx.items())[:10])
输出
[('<unk>', 0), ('the', 1), ('i', 2), ('and', 3), ('of', 4), ('a', 5), ('to', 6), ('was', 7), ('in', 8), ('that', 9)]
给定一句话,输出其对应token的索引
for i in [0, 10]:
print('文本:', tokens[i])
print('索引:', vocab[tokens[i]])
文本: ['the', 'time', 'machine', 'by', 'h', 'g', 'wells']
索引: [1, 19, 50, 40, 2183, 2184, 400]
文本: ['twinkled', 'and', 'his', 'usually', 'pale', 'face', 'was', 'flushed', 'and', 'animated', 'the']
索引: [2186, 3, 25, 1044, 362, 113, 7, 1421, 3, 1045, 1]
整合
def load_corpus_time_machine(max_tokens=-1): #@save
"""返回时光机器数据集的词元索引列表和词表"""
lines = read_time_machine()
tokens = tokenize(lines, 'char')
vocab = Vocab(tokens)
# 因为时光机器数据集中的每个文本行不一定是一个句子或一个段落,
# 所以将所有文本行展平到一个列表中
corpus = [vocab[token] for line in tokens for token in line]
if max_tokens > 0:
corpus = corpus[:max_tokens]
return corpus, vocab
corpus, vocab = load_corpus_time_machine()
len(corpus), len(vocab)
这里用了char词元
(170580, 28)
len(vocab):
28个,26个字母,空格,
corpus = [vocab[token] for line in tokens for token in line]:
返回每一个token对应的下标
corpus长这样
[3, 9, 2, 1, 3, 5, 13, 2, 1, 13, 4, 15, 9, 5, 6, 2, 1, 21, 19, 1, 9...16, 1, 13, 4, 6]
def load_corpus_time_machine(max_tokens=-1):
这个函数干的事:输入一段文本,返回了其所有文本对应下标的列表,以及返回了一个词典