ตัวอย่างการทำเมฆกลุ่มคำใน R ครับ (Windows10 + R > 3.2 + RStudio 0.99.903)
library ที่จะใช้มีสองตัวคือ RLongLexTo (ดูวิธีติดตั้งที่ https://github.com/slphyx/RLongLexTo) กับ wordcloud2 (https://github.com/Lchiffon/wordcloud2)
library(RLongLexTo) library(wordcloud2)
เซ็ต LC_CTYPE ให้ใช้ภาษาไทยครับ
Sys.setlocale("LC_CTYPE","Thai")
จากนั้นก็สร้างtext file ของข้อความที่ต้องการสร้างเมฆกลุ่มคำ ในที่นี้ผมcopyข้อความมาจาก http://king.kapook.com/royal_words_2545.php แล้วสร้างเป็นไฟล์ชื่อtest.txt อันนี้ทำง่ายๆเลยครับโดยการลากเม้าส์ ไฮไลท์ข้อความที่ต้องการบนweb browser (MS Edge) แล้วกด ctlr+c เพื่อcopy แล้วก็เอาไปวางในnotepad (ctrl+v) แล้วก็save โดยที่ตอนเซฟผมเลือก Encoding เป็น ANSI จากนั้นก็ใช้คำสั่ง RLongLexToF เพื่อทำการแยกคำโดยคำสั่งนี้จะสร้างไฟล์outputออกมา(ผมให้ชื่อ outtest.txt ครับ) โดยที่แต่ล่ะคำจะแยกกันโดยมีเครื่องหมาย “|” คั่นอยู่
RLongLexToF(inputfilename = "test.txt",outputfilename = "outtest.txt")
จากนั้นก็อ่านไฟล์ที่แยกคำแล้วมาสร้างเป็นvector ตามนี้ครับ
outtxt<-as.vector(strsplit(readLines("outtest.txt"),"[|]")[[1]])
พอได้vectorของแต่ล่ะคำแล้วก็สร้าง data frame สำหรับนับว่าแต่ล่ะคำนั้นมีความถี่หรือมีจำนวนเท่าใด
wordfreq<-as.data.frame(table(outtxt))
จากนั้นก็เอาตัวแปรสำหรับเก็บความถึ่ของคำนี้ไปสร้างwordcloudได้เลยครับ
wordcloud2(wordfreq,color = "random-light",shape = 'star',backgroundColor = "black")
ส่วนอันนี้ก็เป็นอีกตัวอย่างครับ โดยที่ไฟล์ข้อความผมcopyมาจาก http://king.kapook.com/royal_words_2548.php
RLongLexToF(inputfilename = "test2.txt",outputfilename = "outtest2.txt") outtxt2<-as.vector(strsplit(readLines("outtest2.txt"),"[|]")[[1]]) wordfreq2<-as.data.frame(table(outtxt2)) wordcloud2(wordfreq2)
One thought on “word cloud ภาษาไทยใน R”