斷詞與清理

R 文字分析入門

Maham Faisal Khan

Senior Data Science Content Developer

使用 tidytext

R 文字分析入門

文字斷詞(Tokenizing)

一些自然語言處理(NLP)術語:

  • Bag of words:文件中的字詞彼此獨立
  • 每段獨立文字都是一個文件
  • 每個不重複的字詞是「term」
  • 每次出現的 term 是一個「token」
  • 產生 bag of words 稱為「tokenizing」
R 文字分析入門

使用 unnest_tokens()

tidy_review <- review_data %>% 
  unnest_tokens(word, review)

tidy_review
# A tibble: 229,481 x 4
   date    product                    stars word   
   <chr>   <chr>                      <dbl> <chr>  
 1 2/28/15 iRobot Roomba 650 for Pets     5 you    
 2 2/28/15 iRobot Roomba 650 for Pets     5 would  
 3 2/28/15 iRobot Roomba 650 for Pets     5 not    
# … with 229,478 more rows
R 文字分析入門

計算詞頻

tidy_review %>% 
  count(word) %>% 
  arrange(desc(n))
# A tibble: 10,310 x 2
   word      n
   <chr> <int>
 1 the   11785
 2 it     7905
 3 and    6794
# … with 10,307 more rows
R 文字分析入門

使用 anti_join()

  • 我們想從整理後的資料框移除停用詞(stop words)
  • 你會用 join 來完成

R 文字分析入門

使用 anti_join()

tidy_review2 <- review_data %>% 
  unnest_tokens(word, review) %>% 
  anti_join(stop_words)

tidy_review2
# A tibble: 78,868 x 4
   date     product                    stars word       
   <chr>    <chr>                      <dbl> <chr>      
 1 1/12/15  iRobot Roomba 650 for Pets     4 walk       
 2 1/12/15  iRobot Roomba 650 for Pets     4 rest       
# … with 78,866 more rows
R 文字分析入門

再次計算詞頻

tidy_review2 %>% 
  count(word) %>% 
  arrange(desc(n))
# A tibble: 9,672 x 2
   word         n
   <chr>    <int>
 1 roomba    2286
 2 clean     1204
 3 vacuum     989
# … with 9,669 more rows
R 文字分析入門

一起來練習吧!

R 文字分析入門

Preparing Video For Download...