文本预处理——动手学深度学习02

1、文本预处理

自然语言处理中,原始数据是一系列的字符串,所以要先将数据进行文本预处理,然后才能进行后续的操作。接下来,将介绍数据预处理的步骤。
(1)加载文本数据
(2)分词
(3)建立字典,将每个词映射到一个唯一的索引(index)
(4) 将文本从词的序列转换为索引的序列,方便输入模型

实际上,也有很多现有的工具能用于分词,如spaCyNLTK,这两种主要用于英文的分词;而 jieba 适用于中文分词。

中文分词与英文分词有很大不同,相对来说,中文分词主要是存在着以下问题:
(1)中文存在词的语义比英文更为复杂,中文有很多词一词多义
(2)词汇少
(3)特征稀释
(4) 分类精确率低

2、步骤以及代码

(1)加载数据
所用数据是一部英文小说,即H. G. Well的Time Machine(点击链接可获取数据),作为示例,来展示文本预处理的具体过程。

import collections
import re

def read_time_machine():
    with open('/home/kesci/input/timemachine7163/timemachine.txt', 'r') 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 3221

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

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)

tokens = tokenize(lines)
tokens[0:2]
[['the', 'time', 'machine', 'by', 'h', 'g', 'wells', ''], ['']]

(3)建立字典(这部分代码比较难,特意加了注释)

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

class Vocab(object):
    '''
    1、count_corpus统计词频,得到counter
    2、增删,利用空列表
        pad:二维矩阵长度不一,短句子补token利用pad
        bos:开始token
        eos:结束token
        unk:未登录词当作unk
    3、词到索引号
    '''
    def __init__(self, tokens, min_freq=0, use_special_tokens=False):
        counter = count_corpus(tokens)  # 统计单词出现的频率(字典类型)
        
        self.token_freqs = list(counter.items())
        # print(,self.token_freqs)  打印出的内容为['', 'the', 'time', 'machine']
        
        #记录最终需要维护的token
        self.idx_to_token = []
        
        #将特殊token加入self.idx_to_token
        if use_special_tokens:
            # padding, begin of sentence, end of sentence, unknown
            self.pad, self.bos, self.eos, self.unk = (0, 1, 2, 3)
            self.idx_to_token += ['', '', '', '']
        else:
            self.unk = 0
            self.idx_to_token += ['']
        
        #根据条件将单词加入self.idx_to_token
        self.idx_to_token += [token for token, freq in self.token_freqs
                        if freq >= min_freq and token not in self.idx_to_token]
        #print('哈哈哈',self.idx_to_token)  内容为
                        
        #将索引作为单词的编号
        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]

    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)  # 返回一个字典,记录每个词的出现次数
[('', 0), ('the', 1), ('time', 2), ('machine', 3), ('by', 4), ('h', 5), ('g', 6), ('wells', 7), ('i', 8), ('traveller', 9)]

(4)将词转为索引

for i in range(8, 10):
    print('words:', tokens[i])
    print('indices:', vocab[tokens[i]])
words: ['the', 'time', 'traveller', 'for', 'so', 'it', 'will', 'be', 'convenient', 'to', 'speak', 'of', 'him', '']
indices: [1, 2, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0]
words: ['was', 'expounding', 'a', 'recondite', 'matter', 'to', 'us', 'his', 'grey', 'eyes', 'shone', 'and']
indices: [20, 21, 22, 23, 24, 16, 25, 26, 27, 28, 29, 30]
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值