文本预处理
- 将文本作为字符串加载到内存中
- 将字符串拆分为词元(如单词和字符)
- 建立一个词汇表,将拆分的词元映射到数字索引
- 将文本转换为数字索引序列,方便模型操作
1.读取数据集
import collections
import re
from d2l import torch as d2l
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(f'# 文本总行数: {len(lines)}')
print(lines[0])
print(lines[10])
# 文本总行数: 3221
the time machine by h g wells
twinkled and his usually pale face was flushed and animated the
2.词元化
#文本序列又被拆分成一个词元列表,词元(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', 'matter', 'to', 'us', 'his', 'grey', 'eyes', 'shone', 'and']
['twinkled', 'and', 'his', 'usually', 'pale', 'face', 'was', 'flushed', 'and', 'animated', 'the']
3.词表化
class Vocab:
"""文本词表"""
def __init__(self,tokens=None,min_frep=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#<unk>未知词元
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_frep:
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):
"""统计词元的频率"""
# 这里的tokens是1D列表或2D列表
# 判断 tokens是否有数据,tokens【0】是否为列表形式
if len(tokens) == 0 or isinstance(tokens[0], list):
# 将词元列表展平成一个列表
# line从tokens中取出数据
tokens = [token for line in tokens for token in line]
#可以支持方便、快速的计数,将元素数量统计,然后计数并返回一个字典,键为元素,值为元素个数。
return collections.Counter(tokens)#计数器
#tokens = [token for line in tokens for token in line]
flag=5
for line in tokens:
print(line)
flag-=1
if flag < 0:
break
['the', 'time', 'machine', 'by', 'h', 'g', 'wells']
[]
[]
[]
[]
['i']
#tokens = [token for line in tokens for token in line]
flag = 5
for line in tokens:
for token in line:
print(token)
flag-=1
if flag < 0:
break
the
time
machine
by
h
g
wells
i
#打印前几个高频词元及其索引。
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)]
vocab._token_freqs
[('the', 2261),
('i', 1267),
('and', 1245),
('of', 1155),
('a', 816),
('to', 695),
('was', 552),
('in', 541),
('that', 443),
('my', 440),
('it', 437),
('had', 354),
('me', 281),
('as', 270),
('at', 243),
('for', 221),
('with', 216),
('but', 204),
('time', 200),
('were', 158),
('this', 152),
('you', 137),
...]
vocab.idx_to_token
['<unk>',
'the',
'i',
'and',
'of',
'a',
'to',
'was',
'in',
'that',
'my',
'it',
'had',
'me',
'as',
'at',
'for',
'with',
'but',
'time',
'were',
'this',
'you',
'on',
'then',
'his',
'there',
'he',
'have',
'they',
'from',
'one',
'all',
'not',
'into',
'upon',
'little',
'so',
'is',
'came',
'by',
'some',
'be',
'no',
'could',
'their',
...]
vocab.token_to_idx
{'<unk>': 0,
'the': 1,
'i': 2,
'and': 3,
'of': 4,
'a': 5,
'to': 6,
'was': 7,
'in': 8,
'that': 9,
'my': 10,
'it': 11,
'had': 12,
'me': 13,
'as': 14,
'at': 15,
'for': 16,
'with': 17,
'but': 18,
'time': 19,
'were': 20,
'this': 21,
...}
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]
4.整合所有功能
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)
(170580, 28)
5.小节
-
文本是序列数据的一种最常见的形式之一。
-
为了对文本进行预处理,我们通常将文本拆分为词元,构建词表将词元字符串映射为数字索引,并将文本数据转换为词元索引以供模型操作。