Как создать облака слов для текстовых файлов в каталоге в R

Я пытаюсь создать облако слов для каждого текстового файла в каталоге. Это четыре заявления президента. Я продолжаю получать следующее сообщение:

> cname <- file.path("C:", "texts")
> cname
[1] "C:/texts"

> cname <- file.path("C:\\Users\\BonitaW\\Documents\\DATA630\\texts")
> dir(cname)
[1] "berniesandersspeechtranscript20115.txt"
[2] "hillaryclintonspeechtranscript2015.txt"
[3] "jebbushspeechtranscript2015.txt"       
[4] "randpaulspeechtranscript2015.txt"      
> library(tm)
> docs <- Corpus(DirSource(cname)) 
> summary (docs)
                                   Length
berniesandersspeechtranscript20115.txt 2     
hillaryclintonspeechtranscript2015.txt 2     
jebbushspeechtranscript2015.txt        2     
randpaulspeechtranscript2015.txt       2     
                                   Class            
berniesandersspeechtranscript20115.txt PlainTextDocument
hillaryclintonspeechtranscript2015.txt PlainTextDocument
jebbushspeechtranscript2015.txt        PlainTextDocument
randpaulspeechtranscript2015.txt       PlainTextDocument
                                   Mode
berniesandersspeechtranscript20115.txt list
hillaryclintonspeechtranscript2015.txt list
jebbushspeechtranscript2015.txt        list
randpaulspeechtranscript2015.txt       list
> docs <- tm_map(docs, removePunctuation) 
> docs <- tm_map(docs, removeNumbers)
> docs <- tm_map(docs, removeWords, stopwords("english"))
> library(SnowballC) 
Warning message:
package ‘SnowballC’ was built under R version 3.1.3 
> docs <- tm_map(docs, stemDocument)
> docs <- tm_map(docs, stripWhitespace) 
> docs <- tm_map(docs, PlainTextDocument)
> dtm <- DocumentTermMatrix(docs)
> dtm
<<DocumentTermMatrix (documents: 4, terms: 1887)>>
Non-/sparse entries: 2862/4686
Sparsity           : 62%
Maximal term length: 20
Weighting          : term frequency (tf)
> tdm <- TermDocumentMatrix(docs) 
> tdm
<<TermDocumentMatrix (terms: 1887, documents: 4)>>
Non-/sparse entries: 2862/4686
Sparsity           : 62%
Maximal term length: 20
Weighting          : term frequency (tf)

> library(wordcloud)
> Berniedoc <- wordcloud(names(freq), freq, min.freq=25)   
Warning message:
In wordcloud(names(freq), freq, min.freq = 25) :
american could not be fit on page. It will not be plotted.

Первоначально я мог построить Бернидок, но потерял графику, но теперь она не будет отображаться.

 Berniedoc <- wordcloud(names(freq), freq, min.freq=25)   
Warning messages:
1: In wordcloud(names(freq), freq, min.freq = 25) :
american could not be fit on page. It will not be plotted.
2: In wordcloud(names(freq), freq, min.freq = 25) :
 work could not be fit on page. It will not be plotted.
3: In wordcloud(names(freq), freq, min.freq = 25) :
countri could not be fit on page. It will not be plotted.
4: In wordcloud(names(freq), freq, min.freq = 25) :
year could not be fit on page. It will not be plotted.
5: In wordcloud(names(freq), freq, min.freq = 25) :
new could not be fit on page. It will not be plotted.
6: In wordcloud(names(freq), freq, min.freq = 25) :
see could not be fit on page. It will not be plotted.
7: In wordcloud(names(freq), freq, min.freq = 25) :
and could not be fit on page. It will not be plotted.
8: In wordcloud(names(freq), freq, min.freq = 25) :
can could not be fit on page. It will not be plotted.
9: In wordcloud(names(freq), freq, min.freq = 25) :
time could not be fit on page. It will not be plotted.

Не могли бы вы сказать мне, что я делаю неправильно? Может дело в масштабировании? Или я должен изменить «Бернедок» на что-то другое?


person Bernice Sturdivant    schedule 11.05.2015    source источник
comment
Что ж, это не ошибки, это предупреждения, сообщающие вам, что конкретное слово появляется настолько чаще, что оно слишком велико для печати в устройстве для печати. Возможно, вы пытаетесь напечатать слишком много слов. Было бы полезно иметь воспроизводимый пример. Никакое чтение файла не имеет значения для вашей проблемы; кажется, это исключительно для сюжета. Может быть, попробовать max.words=50 сделать только топ-50.   -  person MrFlick    schedule 11.05.2015
comment
В дополнение к предложению MrFlick ограничить количество терминов, вы можете изменить размер слов с аргументом масштаба для wordcloud. Например, попробуйте scale=c(.5,1), чтобы втиснуть на график больше членов меньшего размера.   -  person lawyeR    schedule 11.05.2015
comment
Где вы определяете переменную freq?   -  person seaotternerd    schedule 12.05.2015


Ответы (3)


Вы должны добавить ограничение «max.words» на количество слов.

Berniedoc <- wordcloud(names(freq), freq, min.freq=25, max.words = 50)
person Schindler    schedule 22.11.2016

Я думаю, что было бы проще с воспроизводимым примером. Я понятия не имею, что такое "C:\\Users\\BonitaW\\Documents\\DATA630\\texts". Но я могу сказать вам, что я только что пришел, чтобы решить очень похожую проблему.

Все, что вам нужно сделать, это поиграть с параметром scale в wordcloud. В частности, с первой цифрой, которая представляет range (а не size).

person elcortegano    schedule 20.09.2017

Как насчет альтернативного подхода с использованием пакета quanteda?

Конечно, вам нужно будет изменить ссылки на каталоги для ваших собственных примеров. Установка размера окна PDF должна убрать предупреждения.

require(quanteda)

# load the files into a quanteda corpus
myCorpus <- corpus(textfile("~/Dropbox/QUANTESS/corpora/inaugural/*.txt"))
ndoc(myCorpus)
## [1] 57

# create a document-feature matrix, removing stopwords
myDfm <- dfm(myCorpus, remove = stopwords("english"))
## Creating a dfm from a corpus ...
## ... lowercasing
## ... tokenizing
## ... indexing 57 documents
## ... shaping tokens into data.table, found 134,024 total tokens
## ... ignoring 174 feature types, discarding 69,098 total features (51.6%)
## ... summing tokens by document
## ... indexing 8,958 feature types
## ... building sparse matrix
## ... created a 57 x 8958 sparse dfm
## ... complete. Elapsed time: 0.256 seconds.

# just do first four
for (i in 1:4) {
    pdf(file = paste0("~/tmp/", docnames(myCorpus)[i], ".pdf"), height=12, width=12)
    textplot_wordcloud(myDfm[i, ])  # pass through any arguments you wish to wordcloud()
    dev.off()
}
person Ken Benoit    schedule 09.07.2015