我正在尝试将网页源读入R并将其作为字符串处理.我试图删除段落并从段落文本中删除html标签.我遇到了以下问题:
我尝试实现一个删除html标签的函数:
cleanFun=function(fullStr)
{
#find location of tags and citations
tagLoc=cbind(str_locate_all(fullStr,"<")[[1]][,2],str_locate_all(fullStr,">")[[1]][,1]);
#create storage for tag strings
tagStrings=list()
#extract and store tag strings
for(i in 1:dim(tagLoc)[1])
{
tagStrings[i]=substr(fullStr,tagLoc[i,1],tagLoc[i,2]);
}
#remove tag strings from paragraph
newStr=fullStr
for(i in 1:length(tagStrings))
{
newStr=str_replace_all(newStr,tagStrings[[i]][1],"")
}
return(newStr)
};
Run Code Online (Sandbox Code Playgroud)
这适用于某些标签,但不适用于所有标签,此失败的示例是跟随字符串:
test="junk junk<a href=\"/wiki/abstraction_(mathematics)\" title=\"abstraction (mathematics)\"> junk junk"
Run Code Online (Sandbox Code Playgroud)
目标是获得:
cleanFun(test)="junk junk junk junk"
Run Code Online (Sandbox Code Playgroud)
但是,这似乎不起作用.我认为它可能与字符串长度或转义字符有关,但我找不到涉及这些的解决方案.
Sco*_*hie 49
这可以通过正则表达式和grep系列来实现:
cleanFun <- function(htmlString) {
return(gsub("<.*?>", "", htmlString))
}
Run Code Online (Sandbox Code Playgroud)
这也适用于同一个字符串中的多个html标签!
Dav*_*son 14
library(rvest)
strip_html <- function(s) {
html_text(read_html(s))
}
Run Code Online (Sandbox Code Playgroud)
示例输出:
> strip_html("junk junk<a href=\"/wiki/abstraction_(mathematics)\" title=\"abstraction (mathematics)\"> junk junk")
[1] "junk junk junk junk"
Run Code Online (Sandbox Code Playgroud)
Pey*_*ton 10
使用的另一种方法,内部tm.plugin.webmining使用XML.
> library(tm.plugin.webmining)
> extractHTMLStrip("junk junk<a href=\"/wiki/abstraction_(mathematics)\" title=\"abstraction (mathematics)\"> junk junk")
[1] "junk junk junk junk"
Run Code Online (Sandbox Code Playgroud)
使用qdap包的方法:
library(qdap)
bracketX(test, "angle")
## > bracketX(test, "angle")
## [1] "junk junk junk junk"
Run Code Online (Sandbox Code Playgroud)