2013-02-22 16 views
6

Vorrei creare un corpus per la raccolta di file HTML scaricati, quindi leggerli in R per il futuro text mining.creare un corpus da molti file html in R

In sostanza, questo è quello che voglio fare:

  • Creare un corpus da più file html.

Ho cercato di usare DirSource:

library(tm) 
a<- DirSource("C:/test") 
b<-Corpus(DirSource(a), readerControl=list(language="eng", reader=readPlain)) 

ma restituisce "parametri di directory non valido"

  • legge nel file HTML dal Corpus tutto in una volta. Non sai come farlo.

  • Analizzali, convertili in testo normale, rimuovi i tag. Molte persone hanno suggerito di utilizzare XML, tuttavia, non ho trovato un modo per elaborare più file. Sono tutti per un singolo file.

Grazie mille.

+0

Provare a utilizzare una barra rovesciata anziché una barra in avanti nella chiamata DirSource. 'C: \ test' –

+0

Che pacchetto sono comandi' Corpus' e 'DirSource'? –

risposta

2

Questo corregge l'errore.

b<-Corpus(a, ## I change DireSource(a) by a 
      readerControl=list(language="eng", reader=readPlain)) 

Ma penso che per leggere il tuo Html devi usare il lettore xml. Qualcosa di simile:

r <- Corpus(DirSource('c:\test'), 
      readerControl = list(reader = readXML),spec) 

Ma è necessario fornire l'argomento spec, che dipende dalla struttura del file. vedere ad esempio readReut21578XML. È un buon esempio di parser xml/html.

0

per leggere tutti i file HTML in un oggetto R è possibile utilizzare

# Set variables 
folder <- 'C:/test' 
extension <- '.htm' 

# Get the names of *.html files in the folder 
files <- list.files(path=folder, pattern=extension) 

# Read all the files into a list 
htmls <- lapply(X=files, 
       FUN=function(file){ 
       .con <- file(description=paste(folder, file, sep='/')) 
       .html <- readLines(.con) 
       close(.con) 
       names(.html) <- file 
       .html 
}) 

che vi darà una lista, e ogni elemento è il contenuto HTML di ogni file.

Pubblicherò dopo averlo analizzato, sono di fretta.

11

Questo dovrebbe farlo. Qui ho una cartella sul mio computer di file HTML (un campione casuale di SO) e ne ho ricavato un corpus, quindi una matrice di termini del documento e poi ho svolto alcune attività di mining di testo banali.

# get data 
setwd("C:/Downloads/html") # this folder has your HTML files 
html <- list.files(pattern="\\.(htm|html)$") # get just .htm and .html files 

# load packages 
library(tm) 
library(RCurl) 
library(XML) 
# get some code from github to convert HTML to text 
writeChar(con="htmlToText.R", (getURL(ssl.verifypeer = FALSE, "https://raw.github.com/tonybreyal/Blog-Reference-Functions/master/R/htmlToText/htmlToText.R"))) 
source("htmlToText.R") 
# convert HTML to text 
html2txt <- lapply(html, htmlToText) 
# clean out non-ASCII characters 
html2txtclean <- sapply(html2txt, function(x) iconv(x, "latin1", "ASCII", sub="")) 

# make corpus for text mining 
corpus <- Corpus(VectorSource(html2txtclean)) 

# process text... 
skipWords <- function(x) removeWords(x, stopwords("english")) 
funcs <- list(tolower, removePunctuation, removeNumbers, stripWhitespace, skipWords) 
a <- tm_map(a, PlainTextDocument) 
a <- tm_map(corpus, FUN = tm_reduce, tmFuns = funcs) 
a.dtm1 <- TermDocumentMatrix(a, control = list(wordLengths = c(3,10))) 
newstopwords <- findFreqTerms(a.dtm1, lowfreq=10) # get most frequent words 
# remove most frequent words for this corpus 
a.dtm2 <- a.dtm1[!(a.dtm1$dimnames$Terms) %in% newstopwords,] 
inspect(a.dtm2) 

# carry on with typical things that can now be done, ie. cluster analysis 
a.dtm3 <- removeSparseTerms(a.dtm2, sparse=0.7) 
a.dtm.df <- as.data.frame(inspect(a.dtm3)) 
a.dtm.df.scale <- scale(a.dtm.df) 
d <- dist(a.dtm.df.scale, method = "euclidean") 
fit <- hclust(d, method="ward") 
plot(fit) 

enter image description here

# just for fun... 
library(wordcloud) 
library(RColorBrewer) 

m = as.matrix(t(a.dtm1)) 
# get word counts in decreasing order 
word_freqs = sort(colSums(m), decreasing=TRUE) 
# create a data frame with words and their frequencies 
dm = data.frame(word=names(word_freqs), freq=word_freqs) 
# plot wordcloud 
wordcloud(dm$word, dm$freq, random.order=FALSE, colors=brewer.pal(8, "Dark2")) 

enter image description here

+1

Bello. Basta aggiungere il parametro 'pattern =". Html "' in 'list.files (...)' in modo che ci possano essere altri file all'interno della cartella (* ad es.* Script R per scaricare dati, README e qualsiasi altro file non html, ovviamente file con "html" all'interno dei loro nomi. –

+0

Grazie, buon consiglio. Ho modificato di conseguenza. – Ben

+0

Per far sì che funzioni correttamente con tm 0.6, convertire il corpus in PlainTextDocument altrimenti non sarà possibile creare un TDM. Fai un <- tm_map (a, PlainTextDocument) – viksit

0

Ho trovato il pacchetto boilerpipeR particolarmente utile per estrarre soltanto il testo "core" di una pagina html.