首先,需要获取提及FIFA和四强球队之一的推文。通过Twitter上的标签来实现这一点,并由于硬件资源的限制,将推文的上限设置为1000条。以下是获取这些推文的代码示例:
ARG.list <- searchTwitter('#ARG #FIFA', n=1000, cainfo="cacert.pem")
ARG.df = twListToDF(ARG.list)
BRA.list <- searchTwitter('#BRA #FIFA', n=1000, cainfo="cacert.pem")
BRA.df = twListToDF(BRA.list)
GER.list <- searchTwitter('#GER #FIFA', n=1000, cainfo="cacert.pem")
GER.df = twListToDF(GER.list)
NED.list <- searchTwitter('#NED #FIFA', n=1000, cainfo="cacert.pem")
NED.df = twListToDF(NED.list)
获取所有推文后,需要清理推文内容,然后检查这些推文的情绪。以下是用来提取清理后的词汇并将它们映射到正面和负面字符串的代码:
score.sentiment = function(sentences, pos.words, neg.words, .progress='none') {
require(plyr)
require(stringr)
scores = laply(sentences, function(sentence, pos.words, neg.words) {
# 使用R的正则表达式全局替换,gsub():
sentence = gsub(":)", 'awsum', sentence)
sentence = gsub('[[:punct:]]', '', sentence)
sentence = gsub('[[:cntrl:]]', '', sentence)
sentence = gsub('\\d+', '', sentence)
# 转换为小写:
sentence = tolower(sentence)
# 分割成单词. str_split在stringr包中
word.list = str_split(sentence, '\\s+')
# 有时列表()层次太多
words = unlist(word.list)
# 将词汇与正面和负面词汇字典进行比较
pos.matches = match(words, pos.words)
neg.matches = match(words, neg.words)
# match()返回匹配项的位置或NA
# 只需要TRUE/FALSE:
pos.matches = !is.na(pos.matches)
neg.matches = !is.na(neg.matches)
# 而且,TRUE/FALSE将被sum()作为1/0处理:
score = sum(pos.matches) - sum(neg.matches)
return(score)
}, pos.words, neg.words, .progress=.progress )
scores.df = data.frame(score=scores, text=sentences)
return(scores.df)
}
# 加载情绪词汇列表
hu.liu.pos = scan('C:/temp/positive-words.txt', what='character', comment.char=';')
hu.liu.neg = scan('C:/temp/negative-words.txt', what='character', comment.char=';')
# 添加词汇到列表
pos.words = c(hu.liu.pos, 'upgrade', 'awsum')
neg.words = c(hu.liu.neg, 'wtf', 'wait','waiting', 'epicfail', 'mechanical',"suspension","no")
一旦有了可以单独为推文打分的明确函数,现在就对推文进行打分,然后将它们转换为因子(参考GitHub代码)。
ARG.scores = score.sentiment(ARG.df$text, pos.words,neg.words, .progress='text')
BRA.scores = score.sentiment(BRA.df$text, pos.words,neg.words, .progress='text')
NED.scores = score.sentiment(NED.df$text,pos.words,neg.words, .progress='text')
GER.scores = score.sentiment(GER.df$text,pos.words,neg.words, .progress='text')
ARG.scores$Team = 'Argentina'
BRA.scores$Team = 'Brazil'
NED.scores$Team = 'Netherland'
GER.scores$Team = 'Germany'
head(all.scores)
all.scores = rbind(ARG.scores, NED.scores, GER.scores,BRA.scores)
一旦有了每条推文的情绪得分,现在尝试总结得分并从中获取有用信息。可以使用以下代码进行总结:
table(all.scores$score,all.scores$Team)
ggplot(data=all.scores) +
geom_bar(mapping=aes(x=score, fill=Team), binwidth=1) +
facet_grid(Team~.) +
theme_bw() + scale_fill_brewer()
从图表中可以清楚地看到,阿根廷是明显的赢家。让将这个数据集总结成一个交叉表。
每个队伍的正面/负面推文百分比
使用不同的参数来得出排名顺序。考虑了以下几点来对队伍进行排序:
使用所有三个标准,可以看到阿根廷是明显的赢家,巴西明显排在第四位。但德国和荷兰非常接近。但使用第三个标准,可以看到德国是与巴西竞争的对手。因此,有了一个明确的排名顺序。预测可以在文章的第一张图片中看到。
不是足球运动的追随者,但这项分析足以让将预测与实际情况进行比较。将自己视为一个无偏见的分析师来做出这个预测。本文中使用的技术是一个过于简化的模型,但这是一个开始的好起点。