【发布时间】:2021-02-05 13:36:36
【问题描述】:
我正在尝试将网页源代码读入 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"
但是,这似乎不起作用。我认为这可能与字符串长度或转义字符有关,但我找不到涉及这些的解决方案。
【问题讨论】:
-
修改了输入代码时出现的一些错误。
-
这里发生了很多事情......首先,这是 R,所以没有
;。您基本上是在寻找gsub和适当的正则表达式(在这种情况下,已在此处回答:stackoverflow.com/questions/10225690/…)。代码还有其他问题(dim(tagLoc)[1]没有做你认为的那样),但我认为这不是你问题的重点