2017-04-23 1 views
0

정지 단어와 문장 토크 나이저를 사용하고 있지만 정지 단어를 포함한 결과를 제공하는 필터링 된 문장을 인쇄 할 때. 문제는 출력에서 ​​불용어를 무시하지 않는다는 것입니다. sentence tokenizer에서 stopwords를 제거하는 방법?문장 토큰 화의 정지 단어

userinput1 = input ("Enter file name:") 
    myfile1 = open(userinput1).read() 
    stop_words = set(stopwords.words("english")) 
    word1 = nltk.sent_tokenize(myfile1) 
    filtration_sentence = [] 
    for w in word1: 
     word = sent_tokenize(myfile1) 
     filtered_sentence = [w for w in word if not w in stop_words] 
     print(filtered_sentence) 

    userinput2 = input ("Enter file name:") 
    myfile2 = open(userinput2).read() 
    stop_words = set(stopwords.words("english")) 
    word2 = nltk.sent_tokenize(myfile2) 
    filtration_sentence = [] 
    for w in word2: 
     word = sent_tokenize(myfile2) 
     filtered_sentence = [w for w in word if not w in stop_words] 
     print(filtered_sentence) 

    stemmer = nltk.stem.porter.PorterStemmer() 
    remove_punctuation_map = dict((ord(char), None) for char in string.punctuation) 

    def stem_tokens(tokens): 
     return [stemmer.stem(item) for item in tokens] 

    '''remove punctuation, lowercase, stem''' 
    def normalize(text): 
     return stem_tokens(nltk.sent_tokenize(text.lower().translate(remove_punctuation_map))) 
    vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english') 

    def cosine_sim(myfile1, myfile2): 
     tfidf = vectorizer.fit_transform([myfile1, myfile2]) 
     return ((tfidf * tfidf.T).A)[0,1] 
    print(cosine_sim(myfile1,myfile2)) 

답변

0

나는 stopwords을 문장에서 직접 삭제할 수 없다고 생각합니다. 문장에서 각 단어를 먼저 분리하거나 nltk.word_tokenize을 사용하여 문장을 분리해야합니다. 각 단어마다 정지 단어 목록에 있는지 확인합니다.

import nltk 
from nltk.corpus import stopwords 
stopwords_en = set(stopwords.words('english')) 

sents = nltk.sent_tokenize("This is an example sentence. We will remove stop words from this") 

sents_rm_stopwords = [] 
for sent in sents: 
    sents_rm_stopwords.append(' '.join(w for w in nltk.word_tokenize(sent) if w.lower() not in stopwords_en)) 

출력 당신은 또한 string.punctuation를 사용하여 문장 부호를 제거 할 수 있습니다

['example sentence .', 'remove stop words'] 

참고 예를 들면 다음과 같습니다.

import string 
stopwords_punctuation = stopwords_en.union(string.punctuation) # merge set together 
+0

string.punctuation 사용 방법은 무엇입니까? @titipata – Muhammad

+0

'import string'과'string.punctuation','stopwords_en.union (string.punctuation)'을 할 수 있습니다. – titipata

+0

난 이것을 구현하려고합니다. 한 가지 더 문제. 위의 코드는 두 문서 간의 코사인 유사성을 제공하지만 두 문서간에 유사성 문장을 표시하고 싶습니다. 어떻게 인쇄 할 수 있습니까? @titipata – Muhammad

관련 문제