【发布时间】:2015-02-05 02:05:42
【问题描述】:
我有以下数据框:
sent1 = data.frame(Sentences=c("abundant bad abnormal activity was accomodative due to 2-face people","strange exciting activity was due to great 2-face people"), user = c(1,2))
以及后面的正负词。
pos = c("abound" , "abounds", "abundant", "exciting", "great")
neg = c("2-face","abnormal", "strange", "bad", "weird")
然后我有以下代码,它拆分每个句子中的唯一单词,然后将它们与 pos 和 neg 字典中的单词匹配。 Pos word 等于 1, neg word 等于 -1。
words = (str_split(unlist(sent1$Sentences)," "))
tmp <- data.frame()
tmn <- data.frame()
for (i in 1:nrow(sent1)) {
for (j in 1:length(words[[i]])) {
for (k in 1:length(pos)){
if (words[[i]][j] == pos[k]) {
tmn <- cbind(i,paste(words[[i]][j-1],words[[i]][j],words[[i]][j+1],sep=" "),1)
tmp <- rbind(tmp,tmn)
}
}
for (m in 1:length(neg)){
if (words[[i]][j] == neg[m]) {
tmn <- cbind(i,paste(words[[i]][j-1],words[[i]][j],words[[i]][j+1],sep=" "),-1)
tmp <- rbind(tmp,tmn)
}
}
}
}
如果我有 1.000 个句子,大约需要 10 分钟...如果我有 1.000,000 行,我可以去度假。你能给我一些建议,如何加快这种方法或如何避免 for 循环...... 非常感谢您。
需要的输出:
user matched word and it's neighbour sentimentScore
1 abundant bad 1
1 abundant bad abnormal -1
1 bad abnormal activity -1
1 was accomodative due 1
1 to 2-face people -1
2 strange exciting -1
2 strange exciting activity 1
2 to great 2-face 1
2 great 2-face people -1
【问题讨论】:
-
您输入了一个非常复杂的代码,希望我们能通读一遍?请输入所需的输出,即您的示例所需的结果!
标签: r