我正在尝试将网页源代码读取到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)
};
这适用于某些标签,但不适用于所有标签,以下字符串为失败的示例:
test="junk junk<a href=\"/wiki/abstraction_(mathematics)\" title=\"abstraction (mathematics)\"> junk junk"
目标是获得:
cleanFun(test)="junk junk junk junk"
然而,这似乎不起作用。我认为这可能与字符串长度或转义字符有关,但我找不到涉及这些字符的解决方案。
发布于 2013-06-21 11:49:31
这可以简单地通过正则表达式和grep系列来实现:
cleanFun <- function(htmlString) {
return(gsub("<.*?>", "", htmlString))
}
这也适用于同一字符串中的多个html标签!
这将在htmlString中查找模式<.*?>
的任何实例,并将其替换为空字符串"“。那个?in .*?
使它不贪婪,所以如果你有多个标签(例如<a> junk </a>
),它将匹配<a>
和</a>
而不是整个字符串。
发布于 2015-12-18 05:54:09
您也可以使用rvest包中的两个函数来执行此操作:
library(rvest)
strip_html <- function(s) {
html_text(read_html(s))
}
输出示例:
> strip_html("junk junk<a href=\"/wiki/abstraction_(mathematics)\" title=\"abstraction (mathematics)\"> junk junk")
[1] "junk junk junk junk"
发布于 2013-06-21 22:54:44
另一种方法是在内部使用XML
的tm.plugin.webmining
。
> library(tm.plugin.webmining)
> extractHTMLStrip("junk junk<a href=\"/wiki/abstraction_(mathematics)\" title=\"abstraction (mathematics)\"> junk junk")
[1] "junk junk junk junk"
https://stackoverflow.com/questions/17227294
复制相似问题