【问题标题】:Remove all punctuation except backslash in R删除R中除反斜杠以外的所有标点符号
【发布时间】:2014-11-26 17:24:11
【问题描述】:

我正在尝试从数据集中提取 html 链接。我正在使用 strsplit 然后 grep 来查找带有链接的子字符串,但结果在字符串的开头或结尾都有不需要的字符....如何仅提取具有所需模式的字符串或保留字符串想要的图案

他就是我目前正在做的事情。

1) 我使用 strplit 和 " " (空格) 作为分隔符来分割一段文本

2)接下来我grep strsplit的结果来找到模式

例如grep("https:\/\/support.google.com\/blogger\/topic\/[0-9]",r)

3) 结果的一些变化如下所示....

https://support.google.com/blogger/topic/12457 
https://support.google.com/blogger/topic/12457.
[https://support.google.com/blogger/topic/12457]  
<<https://support.google.com/blogger/topic/12457>>
https://support.google.com/blogger/topic/12457,
https://support.google.com/blogger/topic/12457),
xxxxxxhttps://support.google.com/blogger/topic/12457),hhhththta
etc...

如何只提取“https://support.google.com/blogger/topic/12457”或提取脏数据后如何删除不需要的标点符号

提前致谢。

【问题讨论】:

  • 如果gsub(".*(http.*\\d).*", "\\1", x)都以数字结尾

标签: r regex strsplit


【解决方案1】:

qdapRegex 包有一个很棒的函数 rm_url 非常适合这个例子。

install.packages('qdapRegex')
library(qdapRegex)

urls <- YOUR_VECTOR_OF_URLS
rm_url(urls, extract = T)

【讨论】:

    【解决方案2】:

    如果数据在某些时候是 HTML,你可以试试这个:

    library(XML)
    urls <- getNodeSet(htmlParse(htmldata), "//a[contains(@href, 'support.google.com')]/@href"))
    

    【讨论】:

      【解决方案3】:

      使用rex 可能会使此类任务更简单一些。

      # generate dataset
      x <- c(
      "https://support.google.com/blogger/topic/12457
      https://support.google.com/blogger/topic/12457.
      https://support.google.com/blogger/topic/12457] 
      <<https://support.google.com/blogger/topic/12457>>
      https://support.google.com/blogger/topic/12457,
      https://support.google.com/blogger/topic/12457),
      xxxxxxhttps://support.google.com/blogger/topic/12457),hhhththta")
      
      # extract urls
      # note you don't have to worry about escaping the html string yourself
      library(rex)    
      re <- rex(
        capture(name = "url",
          "https://support.google.com/blogger/topic/",
          digits
          ))
      
      re_matches(x, re, global = TRUE)[[1]]
      #>                                             url
      #>1 https://support.google.com/blogger/topic/12457
      #>2 https://support.google.com/blogger/topic/12457
      #>3 https://support.google.com/blogger/topic/12457
      #>4 https://support.google.com/blogger/topic/12457
      #>5 https://support.google.com/blogger/topic/12457
      #>6 https://support.google.com/blogger/topic/12457
      #>7 https://support.google.com/blogger/topic/12457
      

      【讨论】:

        猜你喜欢
        • 2012-01-31
        • 2016-03-24
        • 2018-07-26
        • 2013-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多