Webページのソースを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"
ただし、これは機能しないようです。文字列の長さやエスケープ文字が関係しているのではないかと思ったのですが、解決策が見つかりませんでした。