Các lệnh xử lý chuỗi

text analysis
Author

Duc Nguyen

Published

January 29, 2026

1 Xử lý sở hữu cách

Thực tế là ta sẽ loại bỏ dấu 's.

v <- c("electricity's", "it's", "what's")

clean <- gsub(pattern = "'s$", # àm sạch ok
              replacement = "",
              x = v)

clean
[1] "electricity" "it"          "what"       
v <- c("electricity's", "it's", "what's")

clean <- gsub(pattern = "'s\\b", 
              replacement = "",
              x = v)

clean
[1] "electricity" "it"          "what"       
text <- c("electricity's impact on people's life's",
          "it's is a good idea",
          "what's",
          "electricity's")

clean_text <- gsub(pattern = "'s\\b", # cú pháp này mạnh hơn
                   replacement = "", 
                   x = text)

clean_text
[1] "electricity impact on people life" "it is a good idea"                
[3] "what"                              "electricity"                      
library(stringr)

clean <- stringr:::str_remove(string = v, 
                     pattern = "'s$")

clean
[1] "electricity" "it"          "what"       
clean <- stringr:::str_remove(string = v, 
                     pattern = "'s\\b")

clean
[1] "electricity" "it"          "what"       
# lệnh này lọc còn sót chữ [people's], [life's]
clean <- stringr:::str_remove(string = text, 
                     pattern = "'s\\b")

clean
[1] "electricity impact on people's life's"
[2] "it is a good idea"                    
[3] "what"                                 
[4] "electricity"                          

2 Quy trình clean text

chuyển về cùng upper hoặc lower case

clean thô: dùng grep, gsub, which để fix từ

clean ký tự unicode

clean dấu quote

rã token

clean stop word (có thể add thêm word cần loại)

clean synonym

gộp theo topic

xử lý miss spelling

3 Sắp xếp thứ tự vector này theo thứ tự vector kia

a <- c("ok", "yes", "happy", "well", "right", "thanks")

b <- c("right", "thanks", "ok", "yes", "well", "happy")

b_sorted_1 <- b[match(a, b)]

b_sorted_2 <- b[order(match(b, a))]

identical(a, b)
[1] FALSE
identical(a, b_sorted_1)
[1] TRUE
identical(a, b_sorted_2)
[1] TRUE