一、說明
網上提供的一個例子,做了修改與訂正。
二、程序
#調入分詞的庫
library("rJava")
library("Rwordseg")
#調入繪制詞雲的庫
library("RColorBrewer")
library("wordcloud")
#讀入數據(特別注意,read.csv竟然可以讀取txt的文本)
myfile<-read.csv(file.choose(),header=FALSE)
#預處理,這步可以將讀入的文本轉換為可以分詞的字符,沒有這步不能分詞
myfile.res <- myfile[myfile!=" "]
#分詞,並將分詞結果轉換為向量
myfile.words <- unlist(lapply(X = myfile.res,FUN = segmentCN))
#剔除URL等各種不需要的字符,還需要刪除什么特殊的字符可以依樣畫葫蘆在下面增加gsub的語句
myfile.words <- gsub(pattern="http:[a-zA-Z\\/\\.0-9]+","",myfile.words)
myfile.words <- gsub("\n","",myfile.words)
myfile.words <- gsub(" ","",myfile.words)
#去掉停用詞
data_stw=read.table(file=file.choose(),colClasses="character")
stopwords_CN=c(NULL)
for(i in 1:dim(data_stw)[1]){
stopwords_CN=c(stopwords_CN,data_stw[i,1])
}
for(j in 1:length(stopwords_CN)){
myfile.words <- subset(myfile.words,myfile.words!=stopwords_CN[j])
}
#過濾掉1個字的詞
myfile.words <- subset(myfile.words, nchar(as.character(myfile.words))>1)
#統計詞頻
myfile.freq <- table(unlist(myfile.words))
myfile.freq <- rev(sort(myfile.freq))
#myfile.freq <- data.frame(word=names(myfile.freq),freq=myfile.freq);
#按詞頻過濾詞,過濾掉只出現過一次的詞,這里可以根據需要調整過濾的詞頻數
#特別提示:此處注意myfile.freq$Freq大小寫
myfile.freq2=subset(myfile.freq, myfile.freq$Freq>=10)
#繪制詞雲
#設置一個顏色系:
mycolors <- brewer.pal(8,"Dark2")
#設置字體
windowsFonts(myFont=windowsFont("微軟雅黑"))
#畫圖
wordcloud(myfile.freq2$word,myfile.freq2$Freq,min.freq=10,max.words=Inf,random.order=FALSE,
random.color=FALSE,colors=mycolors,family="myFont")
library("rJava")
library("Rwordseg")
#調入繪制詞雲的庫
library("RColorBrewer")
library("wordcloud")
#讀入數據(特別注意,read.csv竟然可以讀取txt的文本)
myfile<-read.csv(file.choose(),header=FALSE)
#預處理,這步可以將讀入的文本轉換為可以分詞的字符,沒有這步不能分詞
myfile.res <- myfile[myfile!=" "]
#分詞,並將分詞結果轉換為向量
myfile.words <- unlist(lapply(X = myfile.res,FUN = segmentCN))
#剔除URL等各種不需要的字符,還需要刪除什么特殊的字符可以依樣畫葫蘆在下面增加gsub的語句
myfile.words <- gsub(pattern="http:[a-zA-Z\\/\\.0-9]+","",myfile.words)
myfile.words <- gsub("\n","",myfile.words)
myfile.words <- gsub(" ","",myfile.words)
#去掉停用詞
data_stw=read.table(file=file.choose(),colClasses="character")
stopwords_CN=c(NULL)
for(i in 1:dim(data_stw)[1]){
stopwords_CN=c(stopwords_CN,data_stw[i,1])
}
for(j in 1:length(stopwords_CN)){
myfile.words <- subset(myfile.words,myfile.words!=stopwords_CN[j])
}
#過濾掉1個字的詞
myfile.words <- subset(myfile.words, nchar(as.character(myfile.words))>1)
#統計詞頻
myfile.freq <- table(unlist(myfile.words))
myfile.freq <- rev(sort(myfile.freq))
#myfile.freq <- data.frame(word=names(myfile.freq),freq=myfile.freq);
#按詞頻過濾詞,過濾掉只出現過一次的詞,這里可以根據需要調整過濾的詞頻數
#特別提示:此處注意myfile.freq$Freq大小寫
myfile.freq2=subset(myfile.freq, myfile.freq$Freq>=10)
#繪制詞雲
#設置一個顏色系:
mycolors <- brewer.pal(8,"Dark2")
#設置字體
windowsFonts(myFont=windowsFont("微軟雅黑"))
#畫圖
wordcloud(myfile.freq2$word,myfile.freq2$Freq,min.freq=10,max.words=Inf,random.order=FALSE,
random.color=FALSE,colors=mycolors,family="myFont")
三、結果