Skip to content

Instantly share code, notes, and snippets.

@almogsi
Last active August 19, 2019 21:55
Show Gist options
  • Select an option

  • Save almogsi/bd56a39dc270869c3c58503b462b442c to your computer and use it in GitHub Desktop.

Select an option

Save almogsi/bd56a39dc270869c3c58503b462b442c to your computer and use it in GitHub Desktop.
This code snippet takes a vector of strings and calculates the percentage of passive voice in the input text. It uses Stanford NLP tool and coreNLP for R.
library(rJava)
library(coreNLP)
initCoreNLP()
#in this case, 'test' is a data frame with a col named 'text'
for (i in 1:dim(test)[1]) {
cat(paste0(i / dim(test)[1] * 100, '% completed'))
ann <- annotateString(paste(test$text[i]), format = c("obj"), outputFile = NA, includeXSL = FALSE)
gd <- getDependency(ann)
passive_sub <- length(gd$type[gd$type=="nsubjpass"])/length(gd$type[gd$type!="punct"])
passive_aux <- length(gd$type[gd$type=="auxpass"])/length(gd$type[gd$type!="punct"])
passive_age <- length(gd$type[gd$type=="nmod:agent"])/length(gd$type[gd$type!="punct"])
# here i create three metrics of passives in the input data frame. i prefer using passive_aux as my main metric
test$passive_sub[i] <- as.numeric(passive_sub)
test$passive_aux[i] <- as.numeric(passive_aux)
test$passive_age[i] <- as.numeric(passive_age) #passives with by-phrases
if (i == dim(test)[1]) cat(': Done')
else cat('\014')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment