복붙노트

[PYTHON] NLTK와 scikit-learn에서 텍스트 형태소 분석과 구두점 제거를 결합

PYTHON

NLTK와 scikit-learn에서 텍스트 형태소 분석과 구두점 제거를 결합

저는 NLTK와 scikit-learn의 CountVectorizer를 조합하여 단어 및 토큰 화를 형태소 분석에 사용하고 있습니다.

아래는 CountVectorizer의 일반적인 사용 예입니다.

from sklearn.feature_extraction.text import CountVectorizer

vocab = ['The swimmer likes swimming so he swims.']
vec = CountVectorizer().fit(vocab)

sentence1 = vec.transform(['The swimmer likes swimming.'])
sentence2 = vec.transform(['The swimmer swims.'])

print('Vocabulary: %s' %vec.get_feature_names())
print('Sentence 1: %s' %sentence1.toarray())
print('Sentence 2: %s' %sentence2.toarray())

어느 것이 인쇄 할 것인가?

Vocabulary: ['he', 'likes', 'so', 'swimmer', 'swimming', 'swims', 'the']
Sentence 1: [[0 1 0 1 1 0 1]]
Sentence 2: [[0 0 0 1 0 1 1]]

자, 내가 정지 단어를 제거하고 단어를 스템 핑한다고 가정 해 봅시다. 하나의 옵션은 그렇게하는 것입니다 :

from nltk import word_tokenize          
from nltk.stem.porter import PorterStemmer

#######
# based on http://www.cs.duke.edu/courses/spring14/compsci290/assignments/lab02.html
stemmer = PorterStemmer()
def stem_tokens(tokens, stemmer):
    stemmed = []
    for item in tokens:
        stemmed.append(stemmer.stem(item))
    return stemmed

def tokenize(text):
    tokens = nltk.word_tokenize(text)
    stems = stem_tokens(tokens, stemmer)
    return stems
######## 

vect = CountVectorizer(tokenizer=tokenize, stop_words='english') 

vect.fit(vocab)

sentence1 = vect.transform(['The swimmer likes swimming.'])
sentence2 = vect.transform(['The swimmer swims.'])

print('Vocabulary: %s' %vect.get_feature_names())
print('Sentence 1: %s' %sentence1.toarray())
print('Sentence 2: %s' %sentence2.toarray())

어떤 지문 :

Vocabulary: ['.', 'like', 'swim', 'swimmer']
Sentence 1: [[1 1 1 1]]
Sentence 2: [[1 0 1 1]]

하지만이 두 번째 버전에서 구두점 문자를 제거하는 가장 좋은 방법은 무엇입니까?

해결법

  1. ==============================

    1.몇 가지 옵션이 있습니다. 토큰 화 전에 구두점을 제거하십시오. 그러나 이것은 의미하지는 않을 것입니다 ->

    몇 가지 옵션이 있습니다. 토큰 화 전에 구두점을 제거하십시오. 그러나 이것은 의미하지는 않을 것입니다 ->

    import string
    
    def tokenize(text):
        text = "".join([ch for ch in text if ch not in string.punctuation])
        tokens = nltk.word_tokenize(text)
        stems = stem_tokens(tokens, stemmer)
        return stems
    

    또는 토큰 화 후에 구두점을 제거하십시오.

    def tokenize(text):
        tokens = nltk.word_tokenize(text)
        tokens = [i for i in tokens if i not in string.punctuation]
        stems = stem_tokens(tokens, stemmer)
        return stems
    

    위의 코드는 작동하지만 동일한 텍스트를 여러 번 반복하므로 다소 느립니다.

    숫자 제거 또는 불용어 제거 또는 소문자 제거 등과 같은 더 많은 단계가있는 경우

    가능한 한 많은 단계를 함께하는 것이 더 좋을 것입니다. 여기에 데이터에 사전 처리 단계가 더 필요한 경우 더 효율적인 몇 가지 대답이 있습니다.

  2. from https://stackoverflow.com/questions/26126442/combining-text-stemming-and-removal-of-punctuation-in-nltk-and-scikit-learn by cc-by-sa and MIT license