DataWhale 팀 펀치 학습 캠프 task02-1

텍스트 전처리

: 텍스트이 섹션은 일반적으로 네 전처리 단계를 포함하는 텍스트 데이터를 공통의 전처리 공정, 기술, 시퀀스 데이터의 종류는 문서가 문자 또는 단어의 시퀀스로 간주 될 수있다
1. 읽기 텍스트
2 워드
3. 사전을 구축, 각 단어는 고유 인덱스 (색인)에 매핑
4. 시퀀스 인덱스에 단어 순서에서 텍스트, 편리한 입력 모델을

텍스트 읽어
우리는 텍스트 전처리의 특정 프로세스를 보여주기 위해, 예를 들어, 영어 소설, 즉 HG 우물의 타임 머신을 사용합니다.

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]

[ 'H', 'G', '웰' ''의 ''은 ','시각 ','컴퓨터 ''] [ ']

사전 구축
처리 모델을 촉진하기 위해, 우리는 문자열을 숫자로 변환해야합니다. 우리가 사전 (어휘)를 구축 할 필요가 그래서, 고유 인덱스 번호로 각 단어를 매핑합니다.

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

단어 : [ '이', '시간', '여행', '그래서', '가', '편리' '수' '것' '에 대한', '말하기', '에', '의' '그' '']
지수 : 2, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0] 1
단어 : "이었다 ''이 해설하는 ' '우리', '자기', '회색'에 ''A ','심원 ','사항 ','눈 ','빛나는 ''및 ']
지수 : 20, 21, 22, 23 24, 16, 25, 26, 27, 28, 29, 30]

기존의 도구를 사용하여 워드 분할
방식은 앞에서 설명한 단어는 매우 간단합니다 우리는, 그것은 적어도 다음과 같은 단점이 있습니다 :

1. 문장 부호는 일반적으로 의미 정보를 제공 할 수 있습니다, 그러나 우리는 그것을 직접 폐기 접근
2. 유사한, "하지 않습니다"안된다 " " 같은 단어를 잘못 처리 할 것
"박사를 3 유사"씨 "에 "이 단어는 잘못 처리한다

우리는 이러한 문제의 더 복잡한 규칙의 도입에 의해 해결 있지만, 사실은, 기존 도구의 숫자는 우리가 간단히 두 사람 개요, 좋은 단어가 될 수있다 할 수있다 : 적응하고 NLTK를.

다음은 간단한 예입니다 :

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

적응 :

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

[ '미스터', '첸', '없다', '로', '내', '제안'을 '동의'하지 ''. ']

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

[ '미스터', '첸', '없다', '로', '내', '제안'을 '동의'하지 ''. ']

게시 31 개 원래 기사 · 원의 칭찬 0 · 조회수 810

추천

출처blog.csdn.net/qq_44750620/article/details/104315337