動手學深度學習-10 文本預處理

文本是一類序列數據,一篇文章可以看作是字符或單詞的序列,本節將介紹文本數據的常見預處理步驟,預處理通常包括四個步驟:

  1. 讀入文本
  2. 分詞
  3. 建立字典,將每個詞映射到一個唯一的索引(index)
  4. 將文本從詞的序列轉換爲索引的序列,方便輸入模型

讀入文本

我們用一部英文小說,即H. G. Well的Time Machine,作爲示例,展示文本預處理的具體過程。

鏈接:http://www.gutenberg.org/ebooks/35

import collections  #容器
import re

def read_time_machine():
    with open('/home/kesci/input/timemachine7163/timemachine.txt', 'r') as f:
        #替換功能,正則表達,將所有非a-z的字符替換掉
        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

 

分詞

我們對每個句子進行分詞,也就是將一個句子劃分成若干個詞(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', ''], ['']]

建立字典

爲了方便模型處理,我們需要將字符串轉換爲數字。因此我們需要先構建一個字典(vocabulary),將每個詞映射到一個唯一的索引編號。

class Vocab(object):
    def __init__(self, tokens, min_freq=0, use_special_tokens=False):
        counter = count_corpus(tokens)  # : 
        self.token_freqs = list(counter.items())#變成這樣的形式 [('red', 2), ('green', 10)]
        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 += ['<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]
        #min_freq指的是詞出現的最少的次數
        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)##get() 函數返回指定鍵的值,如果值不在字典中返回默認值
        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)  # 返回一個字典,記錄每個詞的出現次數

 我們看一個例子,這裏我們嘗試用Time Machine作爲語料構建字典

vocab = Vocab(tokens)
print(list(vocab.token_to_idx.items())[0:10])

結果:

[('', 0), ('the', 1), ('time', 2), ('machine', 3), ('by', 4), ('h', 5), ('g', 6), ('wells', 7), ('i', 8), ('traveller', 9)]

#每一個詞對應了一個索引

 

將詞轉爲索引

使用字典,我們可以將原文本中的句子從單詞序列轉換爲索引序列

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]

用現有工具進行分詞

我們前面介紹的分詞方式非常簡單,它至少有以下幾個缺點:

  1. 標點符號通常可以提供語義信息,但是我們的方法直接將其丟棄了
  2. 類似“shouldn't", "doesn't"這樣的詞會被錯誤地處理
  3. 類似"Mr.", "Dr."這樣的詞會被錯誤地處理

我們可以通過引入更復雜的規則來解決這些問題,但是事實上,有一些現有的工具可以很好地進行分詞,我們在這裏簡單介紹其中的兩個:spaCyNLTK

下面是一個簡單的例子:

spacy:https://spacy.io/

NLTK:https://www.nltk.org/

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', '.']
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章