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

文本数据是一类序列数据,通常是字符或单词的序列,在喂给语言模型训练前,要进行统计词频、分词、建立词与数的映射等预处理操作,这将方便后续操作的处理。

读入文本

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

分词

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', ''], ['']]

建立词到数的映射

class Vocab(object):
    def __init__(self, tokens, min_freq=0, use_special_tokens=False):
        counter = count_corpus(tokens)  #counter为一个字典,键为词,值为频数
        self.token_freqs = list(counter.items())
        print(self.token_freqs[:5])
        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 += ['']
        #idx_to_token不断加入频数>min_freq并且当前不在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]
    return collections.Counter(tokens)  # 返回一个字典,记录每个词的出现次数

vocab = Vocab(tokens)
print(list(vocab.token_to_idx.items())[0:10])
# [('the', 2261), ('time', 200), ('machine', 85), ('by', 103), ('h', 1)]

转化原始文本序列为数的序列

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]
"""

现有分词工具

分词是预处理阶段最关键的步骤,上述的分词函数包含的功能极其有限,我们需要更强大的分词工具,这里介绍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])
#['Mr.', 'Chen', 'does', "n't", 'agree', 'with', 'my', 'suggestion', '.']

#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', '.']

有些话说

想几个问题吧,当作回顾与总结吧,也欢迎大家作答…

  1. 文本预处理的目标是什么?
  2. 文本预处理的步骤有哪些?
  3. 如何做分词?分词工具spacy和NLTK怎么用,各自的优缺点有吗,是什么?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值