使用R在几个推文中提取主题标签

时间:2012-08-14 19:01:26

标签: r

我非常想要一个解决方案,从R中的集体推文中提取主题标签。 例如:

[[1]]
[1] "RddzAlejandra: RT @NiallOfficial: What a day for @johnJoeNevin ! Sooo proud t have been there to see him at #London2012 and here in mgar #MullingarShuffle"

[[2]]
[1] "BPOInsight: RT @atos: Atos completes delivery of key IT systems for London 2012 Olympic Games http://t.co/Modkyo2R #london2012"

[[3]]
[1] "BloombergWest: The #Olympics sets a ratings record for #NBC, with 219M viewers tuning in. http://t.co/scGzIXBp #london2012 #tech"

如何解析它以提取所有推文中的#标签词列表。 以前的解决方案只显示第一条推文中的主题标签,并在代码中显示以下错误消息:

> string <-"MonicaSarkar: RT @saultracey: Sun kissed #olmpicrings at #towerbridge #london2012   @ Tower Bridge http://t.co/wgIutHUl"
> 
> [[2]]
Error: unexpected '[[' in "[["
> [1] "ccrews467: RT @BBCNews: England manager Roy Hodgson calls #London2012 a \"wake-up call\": footballers and fans should emulate spirit of #Olympics http://t.co/wLD2VA1K" 
Error: unexpected '[' in "["
> hashtag.regex <- perl("(?<=^|\\s)#\\S+")
> hashtags <- str_extract_all(string, hashtag.regex)
> print(hashtags)
[[1]]
[1] "#olmpicrings" "#towerbridge" "#london2012" 

2 个答案:

答案 0 :(得分:9)

使用regmatchesgregexpr这会给你一个带有每个推文标签的列表,假设hastag是格式#后跟任意数量的字母或数字(我不熟悉twitter):< / p>

foo <- c("RddzAlejandra: RT @NiallOfficial: What a day for @johnJoeNevin ! Sooo proud t have been there to see him at #London2012 and here in mgar #MullingarShuffle","BPOInsight: RT @atos: Atos completes delivery of key IT systems for London 2012 Olympic Games http://t.co/Modkyo2R #london2012","BloombergWest: The #Olympics sets a ratings record for #NBC, with 219M viewers tuning in. http://t.co/scGzIXBp #london2012 #tech")

regmatches(foo,gregexpr("#(\\d|\\w)+",foo))

返回:

[[1]]
[1] "#London2012"       "#MullingarShuffle"

[[2]]
[1] "#london2012"

[[3]]
[1] "#Olympics"   "#NBC"        "#london2012" "#tech"  

答案 1 :(得分:3)

strsplitgrep版本如何:

> lapply(strsplit(x, ' '), function(w) grep('#', w, value=TRUE))
[[1]]
[1] "#London2012"       "#MullingarShuffle"

[[2]]
[1] "#london2012"

[[3]]
[1] "#Olympics"   "#NBC,"       "#london2012" "#tech"      

我无法弄清楚如何在不先拆分的情况下从每个字符串返回多个结果,但我打赌有办法!