文字清理基礎

R 的自然語言處理入門

Kasey Jones

Research Data Scientist

俄羅斯推文資料集

300 萬筆俄羅斯網軍推文

「Russian Troll Tweets」資料集由 fivethirtyeight 提供,包含 2016 年美國選舉期間由機器人產生的 300 萬則推文。

  • 我們將探索前 20,000 則推文
  • 資料包含推文、追蹤者、追蹤中、發布日期、帳號類型等
  • 適合主題建模、分類、命名實體辨識等任務
1 https://github.com/fivethirtyeight/russian-troll-tweets
R 的自然語言處理入門

高頻詞彙

library(tidytext); library(dplyr)
russian_tweets %>%
  unnest_tokens(word, content) %>%
  count(word, sort = TRUE)
# A tibble: 44,318 x 2
   word      n
   <chr> <int>
 1 t.co  18121
 2 https 16003
 3 the    7226
 4 to     5279
 ...
R 的自然語言處理入門

移除停用詞(stop words)

tidy_tweets <- russian_tweets %>%
  unnest_tokens(word, content) %>%
  anti_join(stop_words)
tidy_tweets %>%
  count(word, sort = TRUE)
 1 t.co             18121
 2 https            16003
 3 http              2135
 4 blacklivesmatter  1292
 5 trump             1004
 ...
# A tibble: 1,149 x 2
   word        lexicon
   <chr>       <chr>  
 1 a           SMART  
 2 a's         SMART  
 3 able        SMART  
 4 about       SMART  
 5 above       SMART
R 的自然語言處理入門

自訂停用詞

custom <- add_row(stop_words, word = "https", lexicon = "custom")
custom <- add_row(custom, word = "http", lexicon = "custom")
custom <- add_row(custom, word = "t.co", lexicon = "custom")
russian_tweets %>%
  unnest_tokens(word, content) %>%
  anti_join(custom) %>%
  count(word, sort = TRUE)
R 的自然語言處理入門

最終結果

# A tibble: 43,663 x 2
   word                 n
   <chr>            <int>
 1 blacklivesmatter  1292
 2 trump             1004
 3 black              781
 4 enlist             764
 5 police             745
 6 people             723
 7 cops               693
R 的自然語言處理入門

詞幹提取(Stemming)

  • enlisted ---> enlist
  • enlisting ---> enlist
library(SnowballC)
tidy_tweets <- russian_tweets %>%
  unnest_tokens(word, content) %>%
  anti_join(custom)
# Stemming
stemmed_tweets <- tidy_tweets %>%
  mutate(word = wordStem(word))
R 的自然語言處理入門

詞幹結果

# A tibble: 38,907 x 2
   word               n
   <chr>          <int>
 1 blacklivesmatt  1301
 2 cop             1016
 3 trump           1013
 4 black            848
 5 enlist           809
 6 polic            763
 7 peopl            730
R 的自然語言處理入門

範例時間。

R 的自然語言處理入門

Preparing Video For Download...