2008-08-31 15:38:39
昨日どうしてもre.findallが文章を分割して拾い上げてくれないと文句を云っていた件は、普通の正規表現は改行を飛び越えて対象を処理しないという基本的なことを忘れていたのが原因だった。そんなことに気づくのに二日もかかるとは! といふことで、改行を削除して処理したら何とかなった。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cgi
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.api import urlfetch
import urllib
import re
from re import *
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write("""
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>TechnoratiKWIC</title>
</head>
<body>
<h2>TechnoratiKWIC</h2>
<form action="/kwic" method="post">
<div><input type="text" name="word" ></div>
<div>言語:
<select name="lang">
<option value="ja" selected>日本語</option>
<option value="ko">韓国語</option>
<option value="zh">中国語</option>
<option value="en">英語</option>
<option value="de">ドイツ語</option>
</select>
結果数:
<select name="limit">
<option value="20" selected>20</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</div>
<div><input type="submit" value="検索"></div>
</form>
<p>調べたい語句を入力し、言語と結果数を選び、検索ボタンを押してください。\\
<br />検索は<a href='http://www.technorati.com/' target='blank'\\
>Technorati</a>のウェブサービス(API)を利用します。</p>
<p><img src="http://code.google.com/appengine/images/\\
appengine-noborder-120x30.gif" alt="Powered by Google App Engine" /></p>
</body>
</html>""")
def kwic(word,lang,limit):
re_excerpt = re.compile('<excerpt>.+?</excerpt>')
re_title = re.compile('<title>.+?</title>')
re_link = re.compile('<permalink>.+?</permalink>')
tags = re.compile('<.+?>')
query = {'key':'xxxxxx','query':word.encode('utf-8'),'language':lang,'limit':limit}
url = 'http://api.technorati.com/search?' + urllib.urlencode(query)
xml = urlfetch.fetch(url).content
xml = xml.replace('\n',' ')
results = []
items = re.findall('<item>.+?</item>',xml)
if len(items) < limit:
items.pop()
for item in items:
link = tags.sub('',re_link.search(item).group())
title = tags.sub('',re_title.search(item).group()).decode('utf-8')
excerpt = tags.sub('',re_excerpt.search(item).group()).decode('utf-8')
res = {'excerpt':excerpt,'title':title,'link':link}
results.append(res)
return results
class Result(webapp.RequestHandler):
def post(self):
re_word = re.compile('<strong.+?</strong>')
word = self.request.get('word')
lang = self.request.get('lang')
if lang == ('ja' or 'ko' or 'zh'):
width = 20
else:
width = 30
limit = self.request.get('limit')
results = kwic(word,lang,limit)
table = "<table border='0'>"
for r_item in results:
rtm = r_item['excerpt'].replace('<','<')
rtm = rtm.replace('>','>')
rtm = rtm.replace('"','\"')
blcks = re_word.split(rtm)
keys = re.findall('<strong.+?</strong>',rtm)
if len(blcks) > 1:
for i in (range(len(blcks)-1)):
row = "<tr><td align='right'>"+blcks[i][(len(blcks[i])-width):]+\\
"</td><td align='center'>"+keys[i]+"</td><td>"+blcks[i+1][0:width]+\\
"</td><td><a href='"+r_item['link']+"' target='_blank'>"+\\
r_item['title'][0:10]+"</a></td></tr>\n"
table += row
table += "</table>"
self.response.out.write('<html xmlns="http://www.w3.org/1999/xhtml" \\
xml:lang="' + lang + '">\n<head>\n<meta http-equiv="content-type" \\
content="text/html; charset=UTF-8" />\n<title>TechnoratiKWIC</title>\n\\
</head>\n<body><h2>TechnoratiKWIC</h2>\n<p>Keyword = <strong>')
self.response.out.write(cgi.escape(word))
self.response.out.write('</strong></p>\n')
self.response.out.write(table)
self.response.out.write('<p><img src="http://code.google.com/appengine/\\
images/appengine-noborder-120x30.gif" alt="Powered by Google App Engine" \\
/></p></body></html>')
def main():
application = webapp.WSGIApplication([('/', MainPage),
('/kwic', Result)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
説明は今日は面倒臭いので省略。すみませんね。まあ、読みたい人もいないでしょうが。強調はTechnoratiから返ってきた結果をそのまま使ってみるようにしたので、入力した語と必ずしも一致しない。複合語は分割されてしまうこともある。検索語にスペースが入っていると、変なことになる。そこは解決しなければ。あと、不思議なことにロシア語を検索すると下のような変なことになってしまうのだ。何なんだこれは。

仕方がないのでとりあえずロシア語は外しておこう。それで、technoratikwic.appspot.comにて動かせるようにしてみた。KWICばかり作ってなにしているんだろうと思うけれども、これをやらないと始まらないから。全然理由になっていないけど。