解析推文以提取R中的主题标签

时间:2012-07-18 22:05:28

标签: r parsing hashtag

我想知道是否有人可以快速解决从R中的推文中提取主题标签的问题。 例如,给定以下字符串,如何解析它以使用#标签提取单词?

string <- 'Crowdsourcing is awesome. #stackoverflow'

2 个答案:

答案 0 :(得分:6)

HTML不同,我希望您可以使用正则表达式解析主题标签。

library(stringr)
string <- "#hashtag Crowd#sourcing is awesome. #stackoverflow #question"
# I don't use Twitter, so maybe this regex is not right 
# for the set of allowable hashtag characters.
hashtag.regex <- perl("(?<=^|\\s)#\\S+")
hashtags <- str_extract_all(string, hashtag.regex)

哪个收益率:

> print(hashtags)
[[1]]
[1] "#hashtag"       "#stackoverflow" "#question"     

请注意,如果string实际上是许多推文的向量,这也可以不加修改。它返回一个字符向量列表。

答案 1 :(得分:1)

这样的东西?

string <- c('Crowdsourcing is awesome. #stackoverflow #answer', 
    "another #tag in this tweet")
step1 <- strsplit(string, "#")
step2 <- lapply(step1, tail, -1)
result <- lapply(step2, function(x){
  sapply(strsplit(x, " "), head, 1)
})