如何删除<style>标签之间的所有文字?

Yoa*_*oav 2 r text-mining gsub

我在R上进行文本挖掘任务,我有一个包含一些html文档的语料库.我想删除<style>它们之间的标签和所有文本,最好使用gsub函数.

例:

转过来:

<style>
.s4-tn{
border-left: 1px #0071C5 solid;
padding: 0px;
margin: 0px;
font-family: "Intel Clear", Verdana, verdana, san-serif;
font-size: 15px;
font-weight: lighter;
color: #0071C5; }

.s4-toplinks .s4-tn a.selected:hover{
    color:#1F497D;
    text-decoration: none;
}
</style>
<img id="corner" src="/sites/HR_ETM/SitePages/img/bottom_bar.png"/>
Run Code Online (Sandbox Code Playgroud)

对此:

<img id="corner" src="/sites/HR_ETM/SitePages/img/bottom_bar.png"/>
Run Code Online (Sandbox Code Playgroud)

jdh*_*son 5

我会用 removeNodes

library(XML)
doc <- htmlParse(txt,asText=TRUE)
styleNodes <- getNodeSet(doc, "//style")
removeNodes(styleNodes)
doc

> removeNodes(styleNodes)
NULL
> doc
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head></head>
<body><img id="corner" src="/sites/HR_ETM/SitePages/img/bottom_bar.png"></body>
</html>

> 
Run Code Online (Sandbox Code Playgroud)

要保存您的编辑,XML您可以使用saveXML:

> saveXML(doc)
[1] "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html>\n<head></head>\n<body><img id=\"corner\" src=\"/sites/HR_ETM/SitePages/img/bottom_bar.png\"></body>\n</html>\n"
Run Code Online (Sandbox Code Playgroud)

要选择注释节点,请使用:

commentNodes <- getNodeSet(doc, "//comment()")
Run Code Online (Sandbox Code Playgroud)