簡體   English   中英

Sklearn - 如何從 txt 文件添加自定義停用詞列表

[英]Sklearn - How to add custom stopword list from txt file

我已經使用 Sklearn 完成了 TFIDF,但問題是我不能使用英語單詞作為停用詞,因為我的語言是馬來西亞語(非英語)。 我需要的是導入包含停用詞列表的 txt 文件。

停用詞.txt

saya
cintakan
awak

文件

from sklearn.feature_extraction.text import TfidfVectorizer
corpus = ['Saya benci awak',
          'Saya cinta awak',
          'Saya x happy awak',
          'Saya geram awak',
          'Saya taubat awak']
vocabulary = "taubat".split()
vectorizer = TfidfVectorizer(analyzer='word', vocabulary=vocabulary)
X = vectorizer.fit_transform(corpus)
idf = vectorizer.idf_
print dict(zip(vectorizer.get_feature_names(), idf))

您可以加載特定停用詞的列表並將其作為參數傳遞給TfidfVectorizer 在你的例子中:

from sklearn.feature_extraction.text import TfidfVectorizer
corpus = ['Saya benci awak',
          'Saya cinta awak',
          'Saya x happy awak',
          'Saya geram awak',
          'Saya taubat awak']

# HERE YOU DO YOUR MAGIC: you open your file and load the list of STOP WORDS
stop_words = [unicode(x.strip(), 'utf-8') for x in open('stopword.txt','r').read().split('\n')]

vectorizer = TfidfVectorizer(analyzer='word', stop_words = stop_words)
X = vectorizer.fit_transform(corpus)
idf = vectorizer.idf_
print dict(zip(vectorizer.get_feature_names(), idf))

帶有 stop_words 的輸出:

{u'taubat': 2.09861228866811, u'happy': 2.09861228866811, u'cinta': 2.09861228866811, u'benci': 2.09861228866811, u'geram': 2.09861228866811}

沒有 stop_words 參數的輸出:

{u'benci': 2.09861228866811, u'taubat': 2.09861228866811, u'saya': 1.0, u'awak': 1.0, u'geram': 2.09861228866811, u'cinta': 2.09861228866811, u'happy': 2.09861228866811}

警告:我不會使用 param vocabulary因為它告訴TfidfVectorizer只注意其中指定的單詞,並且通常比說出您想要的單詞更難意識到您想要考慮的所有單詞解雇。 因此,如果您從示例中刪除vocabulary參數並在列表中添加stop_words參數,它將按您的預期工作。

在 Python3 中,我推薦以下過程來攝取您自己的停用詞列表:

  1. 打開相關文件路徑,讀取 .txt 中存儲的停用詞列表:
with open('C:\\Users\\mobarget\\Google Drive\\ACADEMIA\\7_FeministDH for Susan\\Stop words Letters_improved.txt', 'r') as file:
    my_stopwords=[file.read().replace('\n', ',')]
  1. 請參閱矢量化器中的停用詞:
vectorizer = text.CountVectorizer(input='filename', stop_words=my_stopwords, min_df=20)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM