【问题标题】:Extract multiple substrings from a single从单个字符串中提取多个子字符串
【发布时间】:2014-08-28 07:40:14
【问题描述】:

我想从推文中提取标签(推特句柄)。

tweet <- "@me bla bla bla bla @him some text @her"

与:

at <- regexpr('@[[:alnum:]]*', tweet)
handle <- substr(tweet,at+1,at+attr(at,"match.length")-1)

我成功提取了第一个句柄

handle
[1] "me"

但是我无法找到提取其他人的方法,有人知道这样做的方法吗? - 谢谢

【问题讨论】:

    标签: r text


    【解决方案1】:
    library(stringr)
    str_extract_all(tweet,perl("(?<=@)\\w+"))[[1]]
    #[1] "me"  "him" "her"
    

    或使用stringi 进行快速处理

     library(stringi)
     stri_extract_all_regex(tweet, "(?<=@)\\w+")[[1]]
     #[1] "me"  "him" "her"
    

    基准测试

     tweet1 <- rep(tweet, 1e5)
     f1 <- function() {m <- regmatches(tweet1, gregexpr("@[a-z]+", tweet1))[[1]] 
                  substring(m, 2)}
    
     f2 <- function() {stri_extract_all_regex(tweet1, "(?<=@)\\w+")[[1]]}
     f3 <- function() {regmatches(tweet1, gregexpr("(?<=@)[a-z]+", tweet1,perl=T))}
    
     library(microbenchmark)
     microbenchmark(f1(), f2(), f3(), unit="relative")
     #Unit: relative
     # expr      min       lq   median       uq      max neval
     #f1() 5.387274 5.253141 5.143694 5.166854 4.544567   100
     #f2() 1.000000 1.000000 1.000000 1.000000 1.000000   100
     #f3() 5.523090 5.440423 5.301971 5.335775 4.721337   100
    

    【讨论】:

    • 对我来说太快了!不错的建议。
    【解决方案2】:

    我建议:

    tweet <- "@me bla bla bla bla @him some text @her"
    regmatches(tweet, gregexpr("(?<=@)[a-z]+", tweet,perl=T))
    
    ## [[1]]
    ## [1] "me"  "him" "her"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      相关资源
      最近更新 更多