「ハンズオン深い学習学習」のノートのシリーズ - テキスト前処理を

テキストの前処理

テキストは、ステップを前処理一般的なテキストデータがあり、ここで、記事では、文字や単語のシーケンスとして見ることができ、シーケンスデータの一種である、前処理は、一般に、4つの手順が含まれます。

  1. テキストを読みます
  2. 分詞
  3. 辞書確立し、各単語は、一意のインデックス(指数)にマッピングされています
  4. 単語列から変換したテキストを簡単に入力モデルのシーケンスインデックスであります

STEP1:読み込まれたテキスト

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))

STEP2:単語

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]

STEP3:辞書を確立

辞書(語彙)を構築し、各ワードは、プロセスモデルを容易にするために、一意のインデックス番号にマッピングされます。

class Vocab(object):
    def __init__(self, tokens, min_freq=0, use_special_tokens=False):
        counter = count_corpus(tokens)  # : 
        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 += ['', '', '', '']
        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]
    return collections.Counter(tokens)  # 返回一个字典,记录每个词的出现次数

タイムマシンでコーパス辞書を構築するために、次の試み:

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

STEP4:インデックスへの言葉

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

既存のツールとのセグメントの単語

Wordには、我々は先に説明した方法は、それは、少なくとも以下の欠点があり、非常に簡単です:

  1. 句読点は通常、意味情報を提供することができますが、我々はそれが直接廃棄されたアプローチ
  2. 同様に、そのようなAワードが間違って処理することができない「」「いけません」
  3. 「ミスター」と同様に、「博士」などの単語が正しく処理されています

私たちは、これらの問題のより複雑なルールを導入することによって解決することができるが、実際には、我々は簡単に概要それらの2、既存のツールの数は良い言葉することができありますスペイシーNLTKは

以下は簡単な例です:

text = "Mr. Chen doesn't agree with my suggestion."

1.スペイシー

import spacy
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
print([token.text for token in doc])

2. MLTK

from nltk.tokenize import word_tokenize
from nltk import data
data.path.append('/home/kesci/input/nltk_data3784/nltk_data')
print(word_tokenize(text))

おすすめ

転載: www.cnblogs.com/KaifengGuan/p/12309155.html