Skip to content

[已解決] NLTK ImportError: cannot import name ‘stopwords’

Last Updated on 2021-08-30 by Clay

問題描述

今天我在處理英文語料的時候,再次使用了 Python 中經典的自然語言處理工具 —— NLTK 來進行文本的斷詞。但就在我使用以下程式匯入停用詞(stopwords)時:

from nltk.corpus import stopwords



是的,我遭遇到了個奇怪的報錯:

ImportError: cannot import name 'stopwords'

這是個奇怪的問題,我還特地開了個新的虛擬環境試著重新裝裝看 NLTK,發現直接使用上述程式碼匯入應該是沒有問題的啊 —— 唯一的可能就是有人不小心將存放在 nltk 模組中的停用詞不小心刪掉了

神奇的是,這件事情已經發生第二次了,所以我有了上次的經驗,很快地就找到了解決的方法。倒不如說,許多人在 stopwords 上的問題都比我更離奇更難解 …… 哈哈哈。


解決方法

目前我所遇到的問題幾乎都是找不到 nltk 模組中的 stopwords,所以我只需要使用程式重新下載即可。

import nltk
nltk.download('stopwords')



Output:

[nltk_data] Downloading package stopwords to
[nltk_data] /home/clay/nltk_data…
[nltk_data] Unzipping corpora/stopwords.zip.
True


看到以上的訊息,大概就是下載成功了。接下來馬上來試試看是否能正常使用。

from nltk.corpus import stopwords
print(stopwords.words('english'))



Output:

['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've", 'now', 'd', 'll', 'm', 'o', 're', 've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn', "didn't", 'doesn', "doesn't", 'hadn', "hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't", 'ma', 'mightn', "mightn't", 'mustn', "mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't", 'wasn', "wasn't", 'weren', "weren't", 'won', "won't", 'wouldn', "wouldn't"]

如果印出了一大堆的單字,那多半就是能成功使用停用字了。


References


Read More

Tags:

Leave a Reply取消回覆

Exit mobile version