programing

nltk 또는 python을 사용하여 중지 단어를 제거하는 방법

oldcodes 2023. 7. 28. 22:36
반응형

nltk 또는 python을 사용하여 중지 단어를 제거하는 방법

중지 단어를 제거할 데이터 집합이 있습니다.

NLTK를 사용하여 중지 단어 목록을 가져왔습니다.

from nltk.corpus import stopwords

stopwords.words('english')

데이터를 중지 단어 목록과 비교하여 데이터에서 중지 단어를 제거하려면 정확히 어떻게 해야 합니까?

from nltk.corpus import stopwords
# ...
filtered_words = [word for word in word_list if word not in stopwords.words('english')]

다음과 같은 설정 차이를 수행할 수도 있습니다.

list(set(nltk.regexp_tokenize(sentence, pattern, gaps=True)) - set(nltk.corpus.stopwords.words('english')))

nltk 중지 단어를 포함한 모든 유형의 중지 단어를 제외하려면 다음과 같은 작업을 수행할 수 있습니다.

from stop_words import get_stop_words
from nltk.corpus import stopwords

stop_words = list(get_stop_words('en'))         #About 900 stopwords
nltk_words = list(stopwords.words('english')) #About 150 stopwords
stop_words.extend(nltk_words)

output = [w for w in word_list if not w in stop_words]

중지 단어를 제거할 단어 목록(word_list)이 있을 것입니다.다음과 같은 작업을 수행할 수 있습니다.

filtered_word_list = word_list[:] #make a copy of the word_list
for word in word_list: # iterate over word_list
  if word in stopwords.words('english'): 
    filtered_word_list.remove(word) # remove word from filtered_word_list if it is a stopword

아주 간단한 경량 파이썬 패키지가 있습니다.stop-words단지 이를 위하여

먼저 다음을 사용하여 패키지를 설치합니다.pip install stop-words

그런 다음 목록 이해를 사용하여 한 줄로 단어를 제거할 수 있습니다.

from stop_words import get_stop_words

filtered_words = [word for word in dataset if word not in get_stop_words('english')]

이 패키지는 다운로드하기에 매우 가볍고(nltk와 달리), 두 가지 모두에 적합합니다.Python 2그리고.Python 3그리고 다음과 같은 많은 다른 언어들을 위한 스톱 워드가 있습니다.

    Arabic
    Bulgarian
    Catalan
    Czech
    Danish
    Dutch
    English
    Finnish
    French
    German
    Hungarian
    Indonesian
    Italian
    Norwegian
    Polish
    Portuguese
    Romanian
    Russian
    Spanish
    Swedish
    Turkish
    Ukrainian

다음은 (필터링된 단어 목록 대신) 정답을 즉시 문자열로 입력하려는 경우를 위한 것입니다.

STOPWORDS = set(stopwords.words('english'))
text =  ' '.join([word for word in text.split() if word not in STOPWORDS]) # delete stopwords from text

텍스트 클리너 라이브러리를 사용하여 데이터에서 중지 단어를 제거합니다.

다음 링크를 따르십시오. https://yugantm.github.io/textcleaner/documentation.html#remove_stpwrds

이 라이브러리를 사용하려면 다음 단계를 수행합니다.

pip install textcleaner

설치 후:

import textcleaner as tc
data = tc.document(<file_name>) 
#you can also pass list of sentences to the document class constructor.
data.remove_stpwrds() #inplace is set to False by default

위의 코드를 사용하여 중지 단어를 제거합니다.

질문이 좀 오래되었지만, 여기 추가 작업을 할 수 있는 언급할 가치가 있는 새로운 라이브러리가 있습니다.

경우에 따라 중지 단어만 제거하지 않을 수 있습니다.오히려 텍스트 데이터에서 중지 단어를 찾고 이를 리스트에 저장하여 데이터에서 노이즈를 찾고 더 상호 작용적으로 만들 수 있습니다.

도서관의 이름은'textfeatures'다음과 같이 사용할 수 있습니다.

! pip install textfeatures
import textfeatures as tf
import pandas as pd

예를 들어 다음과 같은 문자열 집합이 있다고 가정합니다.

texts = [
    "blue car and blue window",
    "black crow in the window",
    "i see my reflection in the window"]

df = pd.DataFrame(texts) # Convert to a dataframe
df.columns = ['text'] # give a name to the column
df

이제 스톱워드() 함수를 호출하고 원하는 파라미터를 전달합니다.

tf.stopwords(df,"text","stopwords") # extract stop words
df[["text","stopwords"]].head() # give names to columns

결과는 다음과 같습니다.

    text                                 stopwords
0   blue car and blue window             [and]
1   black crow in the window             [in, the]
2   i see my reflection in the window    [i, my, in, the]

보시다시피, 마지막 열에는 해당 문서(기록)에 포함된 중지 단어가 있습니다.

당신은 이 기능을 사용할 수 있습니다, 당신은 모든 단어를 낮출 필요가 있다는 것을 알아야 합니다.

from nltk.corpus import stopwords

def remove_stopwords(word_list):
        processed_word_list = []
        for word in word_list:
            word = word.lower() # in case they arenet all lower cased
            if word not in stopwords.words("english"):
                processed_word_list.append(word)
        return processed_word_list

필터 사용:

from nltk.corpus import stopwords
# ...  
filtered_words = list(filter(lambda word: word not in stopwords.words('english'), word_list))
from nltk.corpus import stopwords 

from nltk.tokenize import word_tokenize 

example_sent = "This is a sample sentence, showing off the stop words filtration."

  
stop_words = set(stopwords.words('english')) 
  
word_tokens = word_tokenize(example_sent) 
  
filtered_sentence = [w for w in word_tokens if not w in stop_words] 
  
filtered_sentence = [] 
  
for w in word_tokens: 
    if w not in stop_words: 
        filtered_sentence.append(w) 
  
print(word_tokens) 
print(filtered_sentence) 

몇 가지 예를 보여드리겠습니다. 먼저 데이터 프레임에서 텍스트 데이터를 추출합니다.twitter_df) 다음과 같이 추가 처리합니다.

     from nltk.tokenize import word_tokenize
     tweetText = twitter_df['text']

그런 다음 토큰화하기 위해 다음 방법을 사용합니다.

     from nltk.tokenize import word_tokenize
     tweetText = tweetText.apply(word_tokenize)

그다음에 스톱워드를 제거하기 위해서는.

     from nltk.corpus import stopwords
     nltk.download('stopwords')

     stop_words = set(stopwords.words('english'))
     tweetText = tweetText.apply(lambda x:[word for word in x if word not in stop_words])
     tweetText.head()

이것이 당신에게 도움이 될 것 같습니다.

가 데터가다같저경우로 Pandas DataFrame사용할 수 있습니다.remove_stopwords기본적으로 NLTK 중지 단어 목록을 사용하는 텍스트테로에서.

import pandas as pd
import texthero as hero
df['text_without_stopwords'] = hero.remove_stopwords(df['text'])

언급URL : https://stackoverflow.com/questions/5486337/how-to-remove-stop-words-using-nltk-or-python

반응형