pydotのdot_parserエラー

Couldn't import dot_parser, loading of dot files will not be possible.

というエラーが出る場合は、/usr/local/lib/python2.7/dist-packages/dot_parser.pyとかのdot_parser.pyを

$ diff -ub dot_parser.py.orig dot_parser.py
--- dot_parser.py.orig	2014-12-20 21:21:51.864889677 +0900
+++ dot_parser.py	2014-12-20 21:22:15.938683519 +0900
@@ -23,8 +23,9 @@
 from pyparsing import ( nestedExpr, Literal, CaselessLiteral, Word, Upcase, OneOrMore, ZeroOrMore,
     Forward, NotAny, delimitedList, oneOf, Group, Optional, Combine, alphas, nums,
     restOfLine, cStyleComment, nums, alphanums, printables, empty, quotedString,
-    ParseException, ParseResults, CharsNotIn, _noncomma, dblQuotedString, QuotedString, ParserElement )
+    ParseException, ParseResults, CharsNotIn, dblQuotedString, QuotedString, ParserElement )
+_noncomma = "".join( [ c for c in printables if c != "," ] )
 class P_AttrList:

という感じで修正しておく。

PythonとElasticsearchで形態素解析

Elasticsearchから取り出してsklearnでテキストデータをゴニョゴニョするときにPython側ではIgoを使って形態素解析とかしていたけど、Elasticsearchでやっている形態素解析と一致しないのもなんだし、Igoを直読みするよりパフォーマンスは落ちると思うけど、辞書管理等々考えるとElasticsearchのanalyze APIを使って形態素解析しちゃった方がシンプルかなっと思い、まとめておく。
まず、PythonでElasticsearchのAnalyze APIが呼べることを以下で確認する。ここでは、Python 2.7を利用している。elasticsearch-pyもインストール済みな想定で、Elasticsearchも起動しておく必要がある。

$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding("utf-8")
>>> from elasticsearch import Elasticsearch
>>> es = Elasticsearch(hosts="localhost:9200")
>>> text=u"今日の天気は晴れです。"
>>> es.indices.analyze(index=u"sample",body=text,params={u"field":u"message"})
{u'tokens': [{u'end_offset': 2, u'token':...

Python2の問題だけど、setdefaultencodingでセットしないとエラーになる。
エンコーディングさえ問題なければ、上記ではsampleインデックスのmessageフィールドのAnalyzerでtextをトークナイズできる。
まぁ、Ubuntuとかであれば、/etc/python2.7/sitecustomize.py の先頭に

import sys
sys.setdefaultencoding("utf-8")

を追加してdefaultencodingをutf-8にしてしまっても良いのかも。(最適な対応方法はわからない…) ほかの環境であれば、/usr/lib/python*/site-packages/sitecustomize.pyあたりに記述すればよい。
ここまで、できてしまえば、sklearnとかで使いたいなら、

class Analyzer:
    """Analyzer"""
    def __init__(self, es, index, field):
        self.es = es
        self.index = index
        self.field = field
    def __call__(self, text):
        if not text:
            return []
        data = self.es.indices.analyze(index=self.index,
                                       body=text, params={"field":self.field})
        tokens = []
        for token in data.get("tokens"):
            tokens.append(token.get("token"))
        return tokens

というような感じで、Analyzerクラスを作っておいて

es = Elasticsearch(hosts="localhost:9200")
analyzer = Analyzer(es, "sample", "message")
vectorizer = TfidfVectorizer(analyzer=analyzer)

みたいな感じで呼べば、いろいろなVectorizerで利用できると思います。

PythonでURLエンコード

urlibのquote/unquoteを利用する。

$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
>>> text=u"今日の天気は晴れです。"
>>> print text
今日の天気は晴れです。
>>> print urllib.quote(text.encode('utf-8'))
%E4%BB%8A%E6%97%A5%E3%81%AE%E5%A4%A9%E6%B0%97%E3%81%AF%E6%99%B4%E3%82%8C%E3%81%A7%E3%81%99%E3%80%82
>>> print urllib.quote(text.encode('euc-jp'))
%BA%A3%C6%FC%A4%CE%C5%B7%B5%A4%A4%CF%C0%B2%A4%EC%A4%C7%A4%B9%A1%A3
>>> print urllib.quote(text.encode('shift_jis'))
%8D%A1%93%FA%82%CC%93V%8BC%82%CD%90%B0%82%EA%82%C5%82%B7%81B
>>> print urllib.unquote('%E4%BB%8A%E6%97%A5%E3%81%AE%E5%A4%A9%E6%B0%97%E3%81%AF%E6%99%B4%E3%82%8C%E3%81%A7%E3%81%99%E3%80%82')
今日の天気は晴れです。