我想从推文中提取标签(推特句柄).
tweet <- "@me bla bla bla bla @him some text @her"
Run Code Online (Sandbox Code Playgroud)
附:
at <- regexpr('@[[:alnum:]]*', tweet)
handle <- substr(tweet,at+1,at+attr(at,"match.length")-1)
Run Code Online (Sandbox Code Playgroud)
我成功提取了第一个句柄
handle
[1] "me"
Run Code Online (Sandbox Code Playgroud)
但是我无法找到提取其他人的方法,有没有人知道这样做的方法?- 谢谢
library(stringr)
str_extract_all(tweet,perl("(?<=@)\\w+"))[[1]]
#[1] "me" "him" "her"
Run Code Online (Sandbox Code Playgroud)
或者stringi
用于快速处理
library(stringi)
stri_extract_all_regex(tweet, "(?<=@)\\w+")[[1]]
#[1] "me" "him" "her"
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我会建议:
tweet <- "@me bla bla bla bla @him some text @her"
regmatches(tweet, gregexpr("(?<=@)[a-z]+", tweet,perl=T))
## [[1]]
## [1] "me" "him" "her"
Run Code Online (Sandbox Code Playgroud)