我在R中使用DirSource从目录创建了一个语料库x。每个文档都是一个文本文件,其中包含相关vBulletin论坛网页的完整HTML。由于它是一个线程,每个文档都有多个单独的帖子,我想用XPath捕获它们。 XPath似乎有效,但我无法将所有捕获的节点都放回语料库中。
如果我的语料库有25个文档,每个文档平均有4个帖子,那么我的新语料库应该有100个文档。我想知道我是否必须做一个循环并创建一个新的语料库。
到目前为止,这是我的混乱工作。来自www.vbulletin.org/forum/中的一个主题的任何来源都是结构的一个例子。
#for stepping through
xt <- x[[5]]
xpath <- "//div[contains(@id,'post_message')]"
getxpath <- function(xt,xpath){
require(XML)
#either parse
doc <- htmlParse(file=xt)
#doc <- htmlTreeParse(tolower(xt), asText = TRUE, useInternalNodes = TRUE)
#don't know which to use
#result <- xpathApply(doc,xpath,xmlValue)
result <- xpathSApply(doc,xpath,xmlValue)
#clean up
result <- gsub(pattern="\\s+",replacement=" ",x=gsub(pattern="\n|\t",replacement=" ",x=result))
result <- c(result[1:length(result)])
free(doc)
#converts group of nodes into 1 data frame with numbers before separate posts
#require(plyr)
#xbythread <- ldply(.data=result,.fun=function(x){unlist(x)})
#don't know what needs to be returned
result <- Corpus(VectorSource(result))
#result <- as.PlainTextDocument(result)
return(result)
}
#call
x2 <- tm_map(x=x,FUN=getxpath,"//div[contains(@id,'post_message')]")
答案 0 :(得分:1)
不久前想出来了。 htmlParse需要isURL = TRUE。
getxpath <- function(xt,xpath){
require(XML);require(tm)
x <- htmlParse(file=u,isURL=TRUE)
resultvector <- xpathSApply(x,xpath,xmlValue)
result <- gsub(pattern="\\s+",replacement=" ",x=gsub(pattern="\n|\t",replacement=" ",x=resultvector))
return(result)
}
res <- getxpath("http://url.com/board.html","//xpath")
要获取所有文件,我使用list.files获取文件列表,使用getxpath()将Map / clusterMap放入列表中,使用do.call将它们放入向量中,使用Corpus(VectorSource(res) ))将它们放入语料库中。