Object Design
Home > Index > Google App Engine からYahoo!日本語形態素解析Webサービスを利用する方法

Google App Engine からYahoo!日本語形態素解析Webサービスを利用する方法

Oreillyの「集合知プログラミング」の付録Cを参考に Google App Engine上から Yahoo!日本語形態素解析Webサービス を利用しようとするとうまくいかない。

調べてみると、quote_plus や urlopen が問題になるようです。

以下のように、 The URL Fetch API に置き換えて形態素解析を呼び出すとうまく作動しました。

splitter.py

from google.appengine.api import urlfetch

from urllib import urlencode
from BeautifulSoup import BeautifulSoup

#pageurl='http://api.jlp.yahoo.co.jp/MAService/V1/parse'
pageurl='http://jlp.yahooapis.jp/MAService/V1/parse'
appid='' # set your app id


def split(text,appid=appid,results='ma',filter='1|2|4|5|9|10'):

    text=text.encode('utf-8')

    res = urlfetch.fetch(pageurl,
        method=urlfetch.POST, 
        headers={'Content-Type':'application/x-www-form-urlencoded'},
        payload=urlencode({
            'appid': appid,
            'sentence' : text,
            'results' : results,
            'response' : 'surface',
            'filter' : filter})
    )

    soup = BeautifulSoup(res.content)
    try :
        return [l.surface.string for l in soup.ma_result.word_list]
    except:
        return []

An Alternative Way ... TinySegmenterを使う

Google App Engine上で、分かち書き(日本語形態素解析する)別の方法として・・・

が、あります。 このTinySegmenterをPythonへ移植版したコード を使う方法があります。 テストしてみましたが、Google App Engineで動きました。

TinySegemnterのPythonへの移植版ページから ダウンロードした、 tiny_segmenter.py を作業ディレクトリに配置して、 以下のように使います。

from tiny_segmenter import TinySegmenter

ts = TinySegmenter()

def split(text):
    r = ts.segment(text)
    return r
関連キーワード