Day 9: TextBlob——对文本进行情感分析
又是“30天學習30種新技術”的一天,我打算暫時把JavaScript放一放,然后學下用Python進行文本處理。本文的重點是情感分析。我在幾年前就對情感分析產生了興趣,當時我想寫一個分析與電影有關的推的應用。這個應用將幫助我決定是否看某部電影。
我 google 了一番,最后發現 [Naive Bayes classifier]( Naive Bayes classifier) 可以解決這個問題。當時我只會Java語言,所以我寫了一個定制的實現,用過一段時間這個應用。我太懶了,沒有提交代碼,所以我的機子掛掉之后,代碼和應用丟失了。現在我把我所有的代碼都提交到 github,我有大概 200 個公開的倉庫 :)
這里我打算介紹下Python的TextBlob。我們首先講一些基礎知識,然后開發一個使用TextBlob API的Flask應用。
TextBlob是什么?
TextBlob是一個用Python編寫的開源的文本處理庫。它可以用來執行很多自然語言處理的任務,比如,詞性標注,名詞性成分提取,情感分析,文本翻譯,等等。你可以在官方文檔閱讀TextBlog的所有特性。
為什么我要關心TextBlob?
我學習TextBlob的原因如下:
我想開發需要進行文本處理的應用。我們給應用添加文本處理功能之后,應用能更好地理解人們的行為,因而顯得更加人性化。文本處理很難做對。TextBlob站在巨人的肩膀上(NTLK),NLTK是創建處理自然語言的Python程序的最佳選擇。
我想學習下如何用 Python 進行文本處理。
安裝 TextBlob
開始 TextBlob 之前,我們首先需要安裝 Python 和 virtualenv。本文中使用 Python 2.7。
官方文檔里提到了很多安裝 TextBlob 的方法。 我們將使用pip install。給不知道pip的開發者,pip是Python的包管理器。我們可以從官網安裝pip。
運行如下命令可以安裝 TextBlob:
mkdir myapp cd myapp virtualenv venv --python=python2.7 . venv/bin/activate pip install textblob curl https://raw.github.com/sloria/TextBlob/master/download_corpora.py | python以上命令將創建myapp目錄,并通過virtualenv激活Python 2.7,然后安裝 textblob 包,最后下載必需的NLTK語料庫。
GitHub 倉庫
今天的demo應用的代碼可從github取得。
應用
demo應用跑在 OpenShift 上 http://showmesentiments-t20.rhcloud.com/ 它是一個非常簡單的使用 TextBlob 情感分析 API 的例子。當用戶輸入的時候,他將看到他輸入的內容是正面的(綠色)、負面的(紅色),還是中性的(橙色)。
https://www.openshift.com/sites/default/files/images/Sentiment%20Analysis%20Demo.png
我們將開發一個使用REST API的簡單的Flask應用。如果你不了解Flask,你可以參考我以前寫的關于Flask的文章。
接著我們將安裝 Flask 框架。首先我們激活 virtualenv,然后使用 pip 安裝 Flask。
. venv/bin/activate pip install flask在我以前寫的關于 Flask 的文章里已經提到,用Flask寫基于REST的web服務相當方便。在 myapp 目錄下創建一個 app.py 文件。內容如下:
from flask import Flask , jsonify, render_template from textblob import TextBlobapp = Flask(__name__)@app.route('/') @app.route('/index') def index():return render_template('index.html')@app.route('/api/v1/sentiment/<message>') def sentiment(message):text = TextBlob(message)response = {'polarity' : text.polarity , 'subjectivity' : text.subjectivity}return jsonify(response)if __name__ == "__main__":app.run(debug=True)以上的代碼做了這些事:
index()函數渲染 html 文件。 在 myapp目錄下創建一個名為模板的新文件夾,然后創建index.html
mkdir templates touch templates/index.html將下面代碼復制到index.html中。這段代碼使用Twitter Bootstrap來增加樣式。我們同時使用了jQuery,在keyup事件時進行REST調用。如果鍵值為退格、制表符、回車、左、右、上、下,那么不進行REST調用。
<html> <head><title>Do sentiment analysis on the text</title><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" type="text/css" href="static/css/bootstrap.css"><style type="text/css">body {padding-top:60px;padding-bottom: 60px;}</style> </head> <body><div class="navbar navbar-inverse navbar-fixed-top"><div class="container"><div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button><a class="navbar-brand" href="#">Run Sentiment Analysis</a></div></div></div><div class="container"><div class="row"><div class="col-md-6"><textarea class="form-control" rows="3" placeholder="Write your text. Minimum length 10 characters"></textarea> </div><div class="col-md-6"><p id="result"></p></div></div></div><script type="text/javascript" src="static/js/jquery.js"></script> <script type="text/javascript">$("textarea").keyup(function(e){console.log('keycode '+e.keyCode);switch (e.keyCode) {case 8: // Backspaceconsole.log('backspace'+e);case 9: // Tabconsole.log('Tab');case 13: // Enterconsole.log('Enter');case 37: // Leftconsole.log('Left');case 38: // Upconsole.log('Up');case 39: // Rightconsole.log('Right');case 40: // Downconsole.log('Down');break;default:var input = $('textarea').val();$('#result').removeClass("alert alert-warning");$('#result').removeClass("alert alert-danger");$('#result').removeClass("alert alert-success");if (input.length > 10){$.get('/api/v1/sentiment/'+input,function(result){if(result.polarity < 0.0){$('#result').addClass("alert alert-danger") .text(input);} else if( result.polarity >= 0.0 && result.polarity <= 0.5){$('#result').addClass("alert alert-warning").text(input);}else{$('#result').addClass("alert alert-success").text(input);}})}}});</script> </body> </html>你可以從我的github 倉庫 中取得 js 和 css 文件。
部署到云端
部署到云端前,先要完成一些配置工作。
注冊一個OpenShift賬號。注冊是完全免費的,Red Hat給每個用戶三枚免費的Gear,可以用Gear運行你的應用。在寫作此文的時候,每個用戶能免費使用總共 1.5 GB 內存和 3 GB 硬盤空間。
安裝 rhc客戶端工具。rhc是ruby gem,因此你的機子上需要裝有 ruby 1.8.7以上版本。 只需輸入 sudo gem install rhc即可安裝 rhc 。如果你已經安裝過了,確保是最新版。運行sudo gem update rhc即可升級。關于配置rhc命令行工具的詳細信息,請參考: https://openshift.redhat.com/community/developers/rhc-client-tools-install
使用 rhc 的 setup 命令配置你的 OpenShift 賬號。這個命令會幫助你創建一個命名空間,同時將你的ssh公鑰上傳至 OpenShift 服務器。
輸入如下命令即可將應用部署到OpenShift:
; rhc create-app day9demo python-2.7 --from-code https://github.com/shekhargulati/day9-textblob-demo-openshift.git --timeout 180這個命令將創建應用,設置公開的DNS,創建私有git倉庫,最后利用你的Github倉庫中的代碼來部署應用。應用將被部署到 http://day9demo-{domain-name}.rhcloud.com 。請用你的賬戶下的域名替換 {domain-name}. 本文中的應用跑在 http://showmesentiments-t20.rhcloud.com/
今天到此為止。多回饋撒~
原文 Day 9: TextBlob--Finding Sentiments in Text
翻譯 SegmentFault
總結
以上是生活随笔為你收集整理的Day 9: TextBlob——对文本进行情感分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Day 8: Harp.JS——现代静态
- 下一篇: Day 10: PhoneGap ——