2016-06-08 23 views
1

我試圖在R中練習製作詞雲,我已經看到在這樣的網站(http://www.r-bloggers.com/building-wordclouds-in-r/)和YouTube上的一些視頻很好地解釋過程。所以我想我會選擇一些隨機的長文件來練習自己。保存文字從網頁中的文字雲在R

我選擇了善意狩獵劇本。它在這裏可用(https://finearts.uvic.ca/writing/websites/writ218/screenplays/award_winning/good_will_hunting.html)。我所做的就是將它複製到Notepad ++中,並開始刪除空行,名稱等,以便在保存之前清理數據。保存爲.csv文件似乎不是一個選項,因此我將它保存爲.txt文件,而R似乎不想將其讀入。

以下兩行都會在R中返回錯誤。

goodwillhunting <- read.csv("C:/Users/MyName/Desktop/goodwillhunting.txt", sep="", stringsAsFactors=FALSE) 
goodwillhunting <- read.table("C:/Users/MyName/Desktop/goodwillhunting.txt", sep="", stringsAsFactors=FALSE) 

我的問題是基於一個html文檔什麼是最好的方法來保存它被讀入用於這樣的事情?我知道你可以在網頁上閱讀的rvest軟件包。 word cloud的教程使用了.csv文件,所以我不確定這是我的最終目標需要達到的目標。

這可能是一種讀取數據的方法嗎?

test = read_html("https://finearts.uvic.ca/writing/websites/writ218/screenplays/award_winning/good_will_hunting.html") 
text = html_text(test) 

任何幫助表示讚賞!

+1

因爲所有你想要的是單詞的列表,你可以使用https://en.wikibooks.org/wiki/R_Programming/Text_Processing#Reading_and_writing_text_files你不能使用'read.table/csv'作爲來自頁面的文本不是表格。 –

+1

您可以嘗試使用readLines導入文檔,然後將每行解析到您的數據結構中。 – Dave2e

+0

謝謝你們兩位!我使用readLines()函數,然後粘貼(文本,崩潰=「」)能夠將所有單詞串起來,並建立一個詞雲! – user137698

回答

2

這裏有一種方法:

library(rvest) 
library(wordcloud) 

test <- read_html("https://finearts.uvic.ca/writing/websites/writ218/screenplays/ 
         award_winning/good_will_hunting.html") 

text <- html_text(test) 
content <- stringi::stri_extract_all_words(text, simplify = TRUE) 

wordcloud(content, min.freq = 10, colors = RColorBrewer::brewer.pal(5,"Spectral")) 

其中給出:

enter image description here

0

下面是一個簡單的例子:

​​