清理一篇部落格文章
在本練習中,你會拿到一段部落格文章的節錄。你的任務是把這段文字清理成更適合機器處理的格式。你需要將文字轉成小寫、做詞形還原(lemmatization),並移除停用字、標點符號,以及非英文字母的字元。
這段節錄已作為字串 blog 提供,並已印出到主控台。停用字清單以 stopwords 提供。
本練習屬於課程
Python 中文本特徵工程
練習說明
- 使用串列生成式,迴圈遍歷
doc,擷取每個 token 的lemma_。 - 使用
stopwords和isalpha()移除停用字與非英文字母的 token。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Load model and create Doc object
nlp = spacy.load('en_core_web_sm')
doc = nlp(blog)
# Generate lemmatized tokens
lemmas = [token.____ for token in ____]
# Remove stopwords and non-alphabetic tokens
a_lemmas = [lemma for lemma in lemmas
if lemma.____ and lemma not in ____]
# Print string after text cleaning
print(' '.join(a_lemmas))