首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >修改R中两个特定词之间的内容

修改R中两个特定词之间的内容
EN

Stack Overflow用户
提问于 2015-07-02 10:34:50
回答 1查看 45关注 0票数 0

我想修改<title> & </title> and <p> & </p>之间的文本。此外,它还可以在数据中重复多次。

代码语言:javascript
复制
<title>  DTC Descriptor </title>
<p>This diagnostic procedure supports the following DTC:</p>
<title>  Conditions for Running the DTC  </title>
<p>This is good</p>

所需产出:

代码语言:javascript
复制
<title>DTC Descriptor</title>
<p>This diagnostic procedure supports the following DTC:</p>
<title>Conditions for Running the DTC</title>
<p>This is good</p>

我已经找到了trim函数,但是我只需要在标签之间应用这个函数。

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-02 11:07:55

这里有两个选项-假设html包含示例文本:

代码语言:javascript
复制
library(XML)
doc <- htmlParse(html, asText = TRUE)
invisible(lapply(getNodeSet(doc, "//text()"), function(txt) xmlValue(txt) <- xmlValue(txt, trim = TRUE) ))

doc
# <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# <html>
# <head><title>DTC Descriptor</title></head>
# <body>
# <p>This diagnostic procedure supports the following DTC:</p><title>Conditions for Running the DTC</title>
# <p>This is good</p>
# </body>
# </html>

cat(gsub("(<[^>]+>)\\s*(.*?)\\s*(</[^>]+>)", "\\1\\2\\3", html))
# <title>DTC Descriptor</title>
# <p>This diagnostic procedure supports the following DTC:</p>
# <title>Conditions for Running the DTC</title>
# <p>This is good</p>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31182225

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档