【问题标题】:Extract Exact Word in R在 R 中提取准确的单词
【发布时间】:2017-07-22 14:21:10
【问题描述】:

我想从变量(实际上是 url)中提取一些确切的单词并创建一个仅包含提取的单词的新变量。检查模式我发现我想要字符 \\"> 和 ",如下所示:

> dados$source[1:20]
 [1] "<a href=\\\"http://twitter.com/download/iphone\\\" rel=\\\"nofollow\\\">Twitter for iPhone</a>"  

 [2] "<a href=\\\"http://twitter.com/download/android\\\" rel=\\\"nofollow\\\">Twitter for Android</a>"

 [3] "<a href=\\\"http://twitter.com\\\" rel=\\\"nofollow\\\">Twitter Web Client</a>" 

我该怎么做?

【问题讨论】:

  • 如果links 是上面的数据,则类似于library(purrr); library(rvest); links %&gt;% map(read_html) %&gt;% map_chr(html_text) 取决于您要获取的内容,这不清楚。
  • dput(dados$source[1:20])
  • @alistaire 抱歉,我要抢设备,即 iPhone、Android、Web 客户端等...

标签: r html-parsing extract


【解决方案1】:

如果您有 HTML,请使用 rvest 之类的 HTML 解析器来解析字符串。一旦获得非 HTML 字符串,就可以使用正则表达式。

library(purrr)    # use lapply and sapply if you prefer
library(rvest)

# representative data
links <- c("<a href=\\\"http://twitter.com/download/iphone\\\" rel=\\\"nofollow\\\">Twitter for iPhone</a>", 
    "<a href=\\\"http://twitter.com/download/android\\\" rel=\\\"nofollow\\\">Twitter for Android</a>", 
    "<a href=\\\"http://twitter.com\\\" rel=\\\"nofollow\\\">Twitter Web Client</a>")

links %>% map(read_html) %>% 
    map_chr(html_text) %>% 
    sub('Twitter (for )?', '', .)

## [1] "iPhone"     "Android"    "Web Client"

【讨论】:

    【解决方案2】:

    我不确定我是否完全理解您要提取的模式。但是,使用正则表达式将是要走的路。 问题中的一个例子:Removing html tags from a string in R

    cleanFun <- function(htmlString) {
      return(gsub("<.*?>", "", htmlString))
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-04
      • 2014-12-30
      相关资源
      最近更新 更多