requestsを入れておくこと。
$ pip3 requests
1つ目の引数に対象ファイルを渡し、2つ目の引数にYahooデベロッパーネットワークで取得したAPIのIDを入れる。
import sys import urllib.parse import requests if len(sys.argv) < 2: print('Usage: python3 yahoo_parse.py target_file app_id') sys.exit() URL = "http://jlp.yahooapis.jp/MAService/V1/parse" TARGET_FILE = sys.argv[1] APP_ID = sys.argv[2] sentence = open(TARGET_FILE).read() post_data = { 'appid': APP_ID, 'results': 'ma', 'sentence': sentence, '' : 'surface,reading,pos,baseform,feature' } res = requests.post(URL, data=post_data) with open(TARGET_FILE + ".wakati.xml", 'wt') as output: output.write(res.text)
これで形態素解析した結果が、「指定ファイル名.wakati.xml」という名前で保存される。
次、XMLのパース。BeautifulSoupで。
pip3 install beautifulsoup4
import sys from bs4 import BeautifulSoup if len(sys.argv) < 2: print('Usage: python3 yahoo_parse_result.py target_file') sys.exit() doc = open(sys.argv[1]).read() soup = BeautifulSoup(doc) for word in soup.find_all('word'): print( word.surface.text.strip(), end=" " )これでわかち書きっぽく標準出力される。 surfaceで表層文字、featureで品詞、baseformで基本形、readingで読みが取れる。