我正在尝试对本地 MongoDB 实例中的大量推文语料进行情感分析,使用的是 Ruby on Rails 4、Ruby 2.1.2 和 Mongoid ORM。
我已经使用了 Mashape.com 上免费提供的 https://loudelement-free-natural-language-processing-service.p.mashape.com API,但它在快速连续推送几百条推文后就开始超时 -- 很明显它不适合处理数万条推文,这是可以理解的。
因此,接下来我想使用在这里推广的 斯坦福 CoreNLP 库:http://nlp.stanford.edu/sentiment/code.html
默认用法除了在 Java 1.8 代码中使用库之外,似乎还需要使用 XML 输入和输出文件。对于我的用例来说,这很麻烦,因为我有成千上万条短推文,而不是长文本文件。我想像使用方法一样使用 CoreNLP 并执行类似于 tweets.each 的循环。
我想一种方法是构建一个包含所有推文的XML文件,然后从Java进程中获取一个推文,解析它并将其放回到DB中,但这感觉很陌生,而且需要大量工作。所以,我很高兴在上面链接的网站上找到了一种方法,可以从命令行运行CoreNLP并接受文本作为stdin,这样我就不必开始摆弄文件系统,而是将文本作为参数提供。然而,为每个推文单独启动JVM与使用无声元素免费情感分析API相比增加了巨大的开销。
现在,我编写的代码又丑又慢,但它能正常工作。尽管如此,我想知道是否有更好的方法在Ruby中运行CoreNLP java程序,而不必开始摆弄文件系统(创建临时文件并将它们作为参数)或编写Java代码?
以下是我正在使用的代码:
def self.mass_analyze_w_corenlp # batch run the method in multiple Ruby processes
todo = Tweet.all.exists(corenlp_sentiment: false).limit(5000).sort(follow_ratio: -1) # start with the "least spammy" tweets based on follow ratio
counter = 0
todo.each do |tweet|
counter = counter+1
fork {tweet.analyze_sentiment_w_corenlp} # run the analysis in a separate Ruby process
if counter >= 5 # when five concurrent processes are running, wait until they finish to preserve memory
Process.waitall
counter = 0
end
end
end
def analyze_sentiment_w_corenlp # run the sentiment analysis for each tweet object
text_to_be_analyzed = self.text.gsub("'"){" "}.gsub('"'){' '} # fetch the text field of DB item strip quotes that confuse the command line
start = "echo '"
finish = "' | java -cp 'vendor/corenlp/*' -mx250m edu.stanford.nlp.sentiment.SentimentPipeline -stdin"
command_string = start+text_to_be_analyzed+finish # assemble the command for the command line usage below
output =`#{command_string}` # run the CoreNLP on the command line, equivalent to system('...')
to_db = output.gsub(/\s+/, "").downcase # since CoreNLP uses indentation, remove unnecessary whitespace
# output is in the format of "neutral, "positive", "negative" and so on
puts "Sentiment analysis successful, sentiment is: #{to_db} for tweet #{text_to_be_analyzed}."
self.corenlp_sentiment = to_db # insert result as a field to the object
self.save! # sentiment analysis done!
end