【问题标题】:How to extract one row from XML using R?如何使用 R 从 XML 中提取一行?
【发布时间】:2015-01-18 05:48:21
【问题描述】:

我从这样的链接中读取数据。

> library(XML)
> url <- "http://biostat.jhsph.edu/~jleek/contact.html"
> html <- htmlTreeParse(url, useInternalNodes=T)

然后我想从中提取第十行来计算它的字符数。我该怎么办?

【问题讨论】:

  • XML 的“一行”是什么意思?你想如何提取它?如果您能提供一个包含样本输入和所需输出的可重现示例,将会很有帮助。
  • 这看起来不像是一个有效的 URL
  • 我添加了一个 URL,我想从中提取第十行。
  • 你的意思是你想把&lt;link rel="stylesheet" href="images/PixelGreen.css" type="text/css"&gt;从html中取出来?

标签: html xml r extract


【解决方案1】:

你在找这个吗?找到 html 开头的第十行(id = main),提取其值,并计算提取内容中的字符数。

> url <- "http://biostat.jhsph.edu/~jleek/contact.html"
> html <- htmlTreeParse(url, useInternalNodes=T)
> xpathSApply(html, "//div[@id = 'main']", xmlValue, trim = TRUE)
[1] "Contact Information\n\n\t\t\t  Address \n\t\t\t  \n\t\t\t  Johns Hopkins University \n\t\t\t  Bloomberg School of Public Health \n\t\t\t  615 North Wolfe Street \n\t\t\t  Baltimore, MD 21205-2179 \n\t\t\t  Phone\n\t\t\t  410-955-1166 (I am much easier to reach by email)\n\t\t\t  Fax\n\t\t\t  410-955-0958\n\t\t\t  Email\n\t\t\t   jleek || jhsph dot edu \n\t\t\t  Twitter\n\t\t\t   @leekgroup\n\t\t\t  Blog\n\t\t\t   Simply Statistics"

然后用nchar()包装上面的内容并将其分配给一个对象,这里是字符。

> characters <- nchar(xpathSApply(html, "//div[@id = 'main']", xmlValue, trim = TRUE))
> characters
[1] 369

您可以删除制表符和换行符,可能使用gsub()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    • 2013-12-26
    • 2021-12-08
    • 1970-01-01
    相关资源
    最近更新 更多