Text Preprocessing

打開 Google, 輸入搜索關鍵詞,顯示上百條搜索結果

打開 Google Translate, 輸入待翻譯文本,翻譯結果框中顯示出翻譯結果

以上二者的共同點便是文本預處理 Pre-Processing

在 NLP 項目中,文本預處理佔據了超過半數的時間,其重要性不言而喻。


當然
也可以利用完備且效率可觀的工具可以快速完成項目
For Example: 我一直在使用的由 哈工大社會計算與信息檢索研究中心開發的 (LTP,Language Technology Platform )語言技術平臺

文本預處理

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

【較爲簡單的步驟,如果需要專門做NLP相關的時候,要進行特殊的預處理】

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

中英文文本預處理的特點

  • 中文文本是沒有像英文的單詞空格那樣隔開的,因此不能直接像英文一樣可以直接用最簡單的空格和標點符號完成分詞。所以一般我們需要用分詞算法來完成分詞。

  • 英文文本的預處理特殊在拼寫問題,很多時候,對英文預處理要包括拼寫檢查,比如“Helo World”這樣的錯誤,我們不能在分析的時候再去糾錯。還有就是詞幹提取(stemming)和詞形還原(lemmatization),主要是因爲英文中一個詞會存在不同的形式,這個步驟有點像孫悟空的火眼金睛,直接得到單詞的原始形態。For Example:" faster “、” fastest " -> " fast ";“ leafs ”、“ leaves ” -> " leaf " 。

本文進行簡要的介紹和實現
詳細可參考:https://www.analyticsvidhya.com/blog/2017/06/word-embeddings-count-word2veec/

讀入文本

引入數據源:http://www.gutenberg.org/ebooks/35【小說 Time Machine】

import collections
import re

def read_time_machine():
    with open('path to 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))

分詞

對每個句子進行分詞,也就是將一個句子劃分成若干個詞(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):
    # 構建Vocab類時注意:句子長度統計與構建字典無關 | 所以不必要進行句子長度統計
    def __init__(self, tokens, min_freq=0, use_special_tokens=False):
        counter = count_corpus(tokens)  #<key,value>:<詞,詞頻> 
        self.token_freqs = list(counter.items()) #去重並統計詞頻
        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]
        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)  # 返回一個字典,記錄每個詞的出現次數

< unk > 較爲特殊,表示爲登錄詞,無論 use_special_token 參數是否爲真,都會用到

將詞轉爲索引

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

for i in range(8, 10):
    print('words:', tokens[i])
    print('indices:', vocab[tokens[i]])

到此,按照常見步驟已經介紹完了

我們對於分詞這一重要關卡需要考慮的更多,上邊實現的簡要分詞許多情形還未完善,只能實現部分特定的分詞

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

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

For Example :

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])
Result:
['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))
Result:
['Mr.', 'Chen', 'does', "n't", 'agree', 'with', 'my', 'suggestion', '.']
發佈了46 篇原創文章 · 獲贊 21 · 訪問量 3432
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章