Task02

文本预处理

文本是一类序列数据,一篇文章可以看作是字符或单词的序列,本节将介绍文本数据的常见预处理步骤,预处理通常包括四个步骤:

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

读入文本

我们用一部英文小说,即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]
# 列表推导式lines = [line for line in f]
# 对lin进行正则表达式替换某些字符
# ^匹配输入字符串的开始位置,在方括号表达式中使用,当该符号在方括号表达式中使用时,表示匹配不接受该方括号表达式中的字符集合
# 要匹配 ^ 字符本身,请使用 \^。
# [^a-z]+表示匹配非a-z的多个字符
    return lines
lines = read_time_machine()
print('# sentences %d' % len(lines))

分词

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

def tokenize(sentences, token='word'):
    """按照一个单词word或者char分割一个句子,默认word"""
    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:5]

建立字典

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

class Vocab(object):
    def __init__(self, tokens, min_freq=0, use_special_tokens=False):
        counter = count_corpus(tokens)  # 对传入的tokens统计
        self.token_freqs = list(counter.items())
        # count.item()返回可遍历的列表
        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 += [token for token, freq in self.token_freqs
                        if freq >= min_freq and token not in 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]
    # 上一句等效于如下
    tokens = []
    for sk in sentences:
        for tk in sk:
            tokens.append(tk)
    return collections.Counter(tokens)  # 返回一个字典,记录每个词的出现次数

将词转为索引

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

注解:以上是一个简洁的分割文本的过程代码,有很多未考虑的地方,基本上就等同于统计字符串。底层数据结构影响性能,好像有什么字典树。

有一些现有工具好用
spacy

NLTK

基本使用见官网api了。
网站有点打不开mmp
回头补啦QAQ

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值