正規表示法基礎

R 的自然語言處理入門

Kasey Jones

Research Data Scientist

什麼是自然語言處理?

NLP:

  • 著重以電腦分析與理解文字

主題:

  • 文字分類
  • 主題模型
  • 命名實體辨識
  • 情緒分析
R 的自然語言處理入門

什麼是正規表示法?

  • 一組用來搜尋文字的字元序列
  • 例如:
    • 用命令列在目錄中找檔案
    • 尋找包含特定樣式的文章
    • 取代特定文字
R 的自然語言處理入門

範例

words <- c("DW-40", "Mike's Oil", "5w30", "Joe's Gas", "Unleaded", "Plus-89")
# Finding Digits
grep("\\d", words, value = TRUE)
[1] 1 3 6
# Finding Apostrophes
grep("\\'", words, value = TRUE)
[1] "Mike's Oil"     "Joe's Gasoline"
R 的自然語言處理入門

正規表示法範例

Pattern Text Matches R Example Text Example
\w 任一英數字元 gregexpr(pattern ='\w', <text>) a
\d 任一數字 gregexpr(pattern ='\d', text) 1
\w+ 任意長度英數字串 gregexpr(pattern ='\w+', text) word
\d+ 任意長度數字 gregexpr(pattern ='\d+', text) 1234
\s 空白字元 gregexpr(pattern ='\s', text) ' '
\S 非空白字元 gregexpr(pattern ='\S', text) word
R 的自然語言處理入門

R 範例

Function Purpose Syntax
grep 在向量中尋找樣式的相符項 grep(pattern ='\w', x = <vector>, value = F)
gsub 取代字串/向量中所有相符項 gsub(pattern ='\d+', replacement = "", x = <vector>)
R 的自然語言處理入門

RegEx 練習

1 https://regexone.com/lesson/matching_characters
R 的自然語言處理入門

開始寫程式!

R 的自然語言處理入門

Preparing Video For Download...