文字清理

Python 中文本特徵工程

Rounak Banik

Data Scientist

文字清理技巧

  • 不必要的空白與逸出序列
  • 標點符號
  • 特殊字元(數字、表情符號等)
  • 停用詞
Python 中文本特徵工程

isalpha()

"Dog".isalpha()
True
"3dogs".isalpha()
False
"12347".isalpha()
False
"!".isalpha()
False
"❤".isalpha()
False
Python 中文本特徵工程

注意事項

  • 縮寫:U.S.AU.K
  • 專有名詞:word2vecxto10x
  • 針對更細緻情況,使用 regex 自訂函式。
Python 中文本特徵工程

移除非英文字母字元

string = """
OMG!!!! This is like    the best thing ever \t\n. 
Wow, such an amazing song! I'm hooked. Top 5 definitely. ❤
"""

import spacy # Generate list of tokens nlp = spacy.load('en_core_web_sm') doc = nlp(string) lemmas = [token.lemma_ for token in doc]
Python 中文本特徵工程

移除非英文字母字元

...
...
# Remove tokens that are not alphabetic
a_lemmas = [lemma for lemma in lemmas 
            if lemma.isalpha() or lemma == '-PRON-']

# Print string after text cleaning print(' '.join(a_lemmas))
'omg this be like the good thing ever wow such an amazing song -PRON- be hooked top definitely'
Python 中文本特徵工程

停用詞(Stopwords)

  • 出現極常見的詞
  • 如冠詞、be 動詞、代名詞等
Python 中文本特徵工程

用 spaCy 移除停用詞

# Get list of stopwords
stopwords = spacy.lang.en.stop_words.STOP_WORDS

string = """ OMG!!!! This is like the best thing ever \t\n. Wow, such an amazing song! I'm hooked. Top 5 definitely. ❤ """
Python 中文本特徵工程

用 spaCy 移除停用詞

...
...
# Remove stopwords and non-alphabetic tokens
a_lemmas = [lemma for lemma in lemmas 
            if lemma.isalpha() and lemma not in stopwords]
# Print string after text cleaning
print(' '.join(a_lemmas))
'omg like good thing wow amazing song hooked definitely'
Python 中文本特徵工程

其他前處理技巧

  • 移除 HTML/XML 標籤
  • 取代重音字元(如 é)
  • 更正拼寫錯誤
Python 中文本特徵工程

注意事項

只使用和你的應用相關的文字前處理技巧。

Python 中文本特徵工程

一起來練習吧!

Python 中文本特徵工程

Preparing Video For Download...