相关疑难解决方法(0)

从R中的字符串中删除html标记

我正在尝试将网页源读入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)

但是,这似乎不起作用.我认为它可能与字符串长度或转义字符有关,但我找不到涉及这些的解决方案.

string r

23
推荐指数
4
解决办法
2万
查看次数

标签 统计

r ×1

string ×1