斷詞與詞形還原

Python 中文本特徵工程

Rounak Banik

Data Scientist

文字來源

  • 新聞文章
  • 推文
  • 留言
Python 中文本特徵工程

讓文字更易於機器處理

  • Dogs, dog
  • reduction, REDUCING, Reduce
  • don't, do not
  • won't, will not
Python 中文本特徵工程

文字前處理技巧

  • 全部轉小寫
  • 移除前後空白
  • 移除標點符號
  • 移除停用詞
  • 展開縮寫
  • 移除特殊字元(數字、表情符號等)
Python 中文本特徵工程

斷詞(Tokenization)

"I have a dog. His name is Hachi."

詞元(Tokens):

["I", "have", "a", "dog", ".", "His", "name", "is", "Hachi", "."]
"Don't do this."

詞元(Tokens):

["Do", "n't", "do", "this", "."]
Python 中文本特徵工程

使用 spaCy 進行斷詞

import spacy

# 載入 en_core_web_sm 模型 nlp = spacy.load('en_core_web_sm')
# 初始化字串 string = "Hello! I don't know what I'm doing here."
# 建立 Doc 物件 doc = nlp(string)
# 產生詞元清單 tokens = [token.text for token in doc] print(tokens)
['Hello','!','I','do',"n't",'know','what','I',"'m",'doing','here','.']
Python 中文本特徵工程

詞形還原(Lemmatization)

  • 將單字轉為基本型
    • reducing, reduces, reduced, reductionreduce
    • am, are, isbe
    • n'tnot
    • 'vehave
Python 中文本特徵工程

使用 spaCy 進行詞形還原

import spacy

# 載入 en_core_web_sm 模型
nlp = spacy.load('en_core_web_sm')
# 初始化字串
string = "Hello! I don't know what I'm doing here."
# 建立 Doc 物件
doc = nlp(string)

# 產生詞元的詞形還原清單 lemmas = [token.lemma_ for token in doc] print(lemmas)
['hello','!','-PRON-','do','not','know','what','-PRON','be','do','here', '.']
Python 中文本特徵工程

一起來練習吧!

Python 中文本特徵工程

Preparing Video For Download...