我正在尝试将单词列表与句子列表进行匹配,并使用匹配的单词和句子形成数据框。例如:
words <- c("far better","good","great","sombre","happy")
sentences <- c("This document is far better","This is a great app","The night skies were sombre and starless", "The app is too good and i am happy using it", "This is how it works")
预期结果(一个数据框)如下:
sentences words
This document is far better better
This is a great app great
The night skies were sombre and starless sombre
The app is too good and i am happy using it good, happy
This is how it works -
我正在使用以下代码来实现这一点。
lengthOfData <- nrow(sentence_df)
pos.words <- polarity_table[polarity_table$y>0]$x
neg.words <- polarity_table[polarity_table$y<0]$x
positiveWordsList <- list()
negativeWordsList <- list()
for(i in 1:lengthOfData){
sentence <- sentence_df[i,]$comment
#sentence <- gsub('[[:punct:]]', "", sentence)
#sentence <- gsub('[[:cntrl:]]', "", sentence)
#sentence <- gsub('\\d+', "", sentence)
sentence <- tolower(sentence)
# get unigrams from the sentence
unigrams <- unlist(strsplit(sentence, " ", fixed=TRUE))
# get bigrams from the sentence
bigrams <- unlist(lapply(1:length(unigrams)-1, function(i) {paste(unigrams[i],unigrams[i+1])} ))
# .. and combine into data frame
words <- c(unigrams, bigrams)
#if(sentence_df[i,]$ave_sentiment)
pos.matches <- match(words, pos.words)
neg.matches <- match(words, neg.words)
pos.matches <- na.omit(pos.matches)
neg.matches <- na.omit(neg.matches)
positiveList <- pos.words[pos.matches]
negativeList <- neg.words[neg.matches]
if(length(positiveList)==0){
positiveList <- c("-")
}
if(length(negativeList)==0){
negativeList <- c("-")
}
negativeWordsList[i]<- paste(as.character(unique(negativeList)), collapse=", ")
positiveWordsList[i]<- paste(as.character(unique(positiveList)), collapse=", ")
positiveWordsList[i] <- sapply(positiveWordsList[i], function(x) toString(x))
negativeWordsList[i] <- sapply(negativeWordsList[i], function(x) toString(x))
}
positiveWordsList <- as.vector(unlist(positiveWordsList))
negativeWordsList <- as.vector(unlist(negativeWordsList))
scores.df <- data.frame(ave_sentiment=sentence_df$ave_sentiment, comment=sentence_df$comment,pos=positiveWordsList,neg=negativeWordsList, year=sentence_df$year,month=sentence_df$month,stringsAsFactors = FALSE)
我有 28k 个句子和 65k 个单词要匹配。上面的代码需要 45 秒才能完成任务。由于当前方法需要大量时间,因此有关如何提高代码性能的任何建议?
编辑:
我只想得到那些与句子中的单词完全匹配的单词。例如 :
words <- c('sin','vice','crashes')
sentences <- ('Since the app crashes frequently, I advice you guys to fix the issue ASAP')
现在对于上述情况,我的输出应该如下:
sentences words
Since the app crashes frequently, I advice you guys to fix crahses
the issue ASAP