动手学深度学习之文本预处理

三世轮回 提交于 2020-02-14 23:17:37

文本预处理

文本是一类典型的序列数据,一篇文章可以看作是字符或单词的序列,当使用神经网络处理文本时,是无法直接作用于字符串的,需要对其进行预处理。本节将介绍文本数据的常见预处理步骤,预处理通常包括四个步骤:

  1. 读入文本;
  2. 分词;
  3. 建立字典将每个词映射到一个唯一的索引(index);
  4. 将文本从词的序列转换为索引的序列,方便输入模型;

读入文本

以H. G. Wells的小说The Time Machine作为示例,展示文本预处理的具体过程。

import collections
import re

def read_time_machine():
    with open(r'C:\Users\25756\Desktop\PythonCode\Pytorch\TheTimeMachinebyWells.txt', 'r',encoding='UTF-8') 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))
# sentences 3583

collections模块:数据结构常用模块,常用类型有:计数器(Counter)/双向队列(deque)/默认字典(defaultdict)/有序字典(OrderedDict)/可命名元组(namedtuple)。Counter对访问对象进行计数并返回一个字典。具体可参考OneMore
re模块:python独有的匹配字符串模块,多基于正则表达式实现。具体可参考Brigth-Python之re模块

分词

对每个句子进行分词,也就是将一个句子划分成若干个词(token),转换为一个词的序列。

lines = read_time_machine()
print('# sentences %d' % len(lines))

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 [list(sentence) for sentence in sentences]
    else:
        print('ERROR: unkown token type '+token)
# 返回一个二维列表,第一个维度是sentences中每个句子,
# 第二个维度是每个句子分词之后得到的单词或序列
tokens = tokenize(lines)
print(tokens[0:2])
[[''], ['the', 'project', 'gutenberg', 'ebook', 'of', 'the', 'time', 'machine', 'by', 'h', 'g', 'wells']]

建立字典

为了方便模型处理,需要将字符串转换为数字,因此需要先构建一个字典(vocabulary),将每个词映射到一个唯一的索引编号。

class Vocab(object):
    def __init__(self, tokens, min_freq=0, use_special_tokens=False):
        '''
        tokens是一个二维列表,包含所有语句的词
        min_freq设定一个词出现的最低频数,小于这个频数的词就忽略
        use_special_tokens是否使用特殊的词
        '''
        # 进行去重与统计词频
        counter = count_corpus(tokens)  # : <key,value> : <词,词频>
        self.token_freqs = list(counter.items())
        self.idx_to_token = []
        if use_special_tokens:
            '''
            padding 用于将batch中所有句子补长至句子最长值
            begin of sentence 添加位于句首的特殊token,表示句子开始
            end of sentence 添加位于句尾的特殊token,表示句子结束
            unknown 输入词可能不存在与语料库中,即未登录词,记为unknown
            '''
            self.pad, self.bos, self.eos, self.unk = (0, 1, 2, 3)
            self.idx_to_token += ['<pad>', '<bos>', '<eos>', '<unk>']
        else:
            self.unk = 0
            self.idx_to_token += ['<unk>']
        self.idx_to_token += [token for token, freq in self.token_freqs
                        if freq >= min_freq and token not in self.idx_to_token]
        # ind_to_token是包含了所有词的列表
        # token_to_inx是一个字典:{'字符':下标}
        self.token_to_idx = dict()
        for idx, token in enumerate(self.idx_to_token):
            self.token_to_idx[token] = idx

    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]
    # 根据下标返回token
    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]

def count_corpus(sentences):
    tokens = [tk for st in sentences for tk in st]  # 将二维列表展平
    return collections.Counter(tokens)  # 返回一个字典,记录每个词的出现次数

vocab = Vocab(tokens)
print(list(vocab.token_to_idx.items())[0:10])
[('<unk>', 0), ('', 1), ('the', 2), ('project', 3), ('gutenberg', 4), ('ebook', 5), ('of', 6), ('time', 7), ('machine', 8), ('by', 9)]

将词转为索引

使用字典,可以将原文本中的句子从单词序列转换为索引序列

for i in range(8, 10):
    print('words:', tokens[i])
    print('indices:', vocab[tokens[i]])
words: ['']
indices: [1]
words: ['title', 'the', 'time', 'machine']
indices: [42, 2, 7, 8]

用现有工具进行分词

以上分词方式非常简单,但有以下几个明显缺点:

  1. 标点符号通常可以提供语义信息,但是我们的方法直接将其丢弃了;
  2. 类似“shouldn’t", "doesn’t"这样的词会被错误地处理;
  3. 类似"Mr.", "Dr."这样的词会被错误地处理;

虽然可以通过引入更复杂的规则来解决这些问题,但事实上有一些现有的工具可以很好地进行分词,在这里简单介绍其中的两个:spaCy/NLTK

下面是一个简单的例子:

text = "Mr. Chen doesn't agree with my suggestion."
'''spaCy'''
import spacy
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
print([token.text for token in doc])
'''NLTK'''
from nltk.tokenize import word_tokenize
from nltk import data
data.path.append('/home/kesci/input/nltk_data3784/nltk_data')
print(word_tokenize(text))
['Mr.', 'Chen', 'does', "n't", 'agree', 'with', 'my', 'suggestion', '.']
['Mr.', 'Chen', 'does', "n't", 'agree', 'with', 'my', 'suggestion', '.']
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!