Back to tech

Python3.xで今日は何の日かを検索する ver2.0

2 min read
Table of Contents

以前に「今日は何の日かを検索する」プログラムを作りました

原因はAPIを仕様変更のため、取得URLを書き換えやごにょごにょすれば簡単に直せますが、それだけだとつまらないため少し変更してみました

準備

  • パッケージ lxmlのインストール

    仕様変更前のapiはテキスト形式のみの出力結果でした.

    しかし、新たにxmlやjson形式で結果を返してくれるようになりました.

    pythonは標準でxmlを解析するパッケージを持っていますが、あえて「lxml」を使います. (私自身使ってみたかった) デフォルトで入っている違い、大幅に解析時間が短いのが特徴です.

    公式ページ:http://lxml.de/index.html

    windows: Unofficialのパッケージ配布サイトに行く (公式が非公式サイトのパッケージでインストールしてよな!って一体・・・)

    Lxmlの最新版をダウンロード 32bitと64bitがあるので注意 http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml

    今回は64bit版で解説 cmdで

    C:\>pip install lxml-3.5.0-cp35-none-win_amd64.whl

    をする

    linux: ターミナルで

    sudo apt-get install python3-lxml

    をする

使い方 1

C:\>python3 TodayTweet_main.py

をすると今日の日付で今日はなんの日かを持ってきます

使い方 2

C:\>python3 TodayTweet_main.py 2月14日

をすると指定した日付に起こった事件などを持ってきます

使い方 3

C:\>python3 TodayTweet_main.py hogehoge

とすると怒られます(エラーが起きる) %d月%d日という形にしないとエラーでます

プログラム

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib.request
import datetime
import sys
import re
from lxml import etree
import os

def main(argv):
    #引数の処理
    if argv is None:
        argv = '%s%s日' % (datetime.datetime.today().month, datetime.datetime.today().day)
        date = urllib.parse.quote(argv)
    pass
    else:
        if re.match(r'\d+\d+日',argv):
            date = urllib.parse.quote(argv)
            pass
        else:
            print ("error!! [ example run:python today.py 4月13日 ]")
            sys.exit("Argument error #1")
            pass
        pass

    #urlの読み込み
    url = 'http://ja.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&titles=' + date
    response = urllib.request.urlopen(url)
    html = response.read()


    #解析
    f = open('today_py_tmp','wb') #TypeError: write() argument must be str, not bytesの回避 ファイルをバイナリモードで開く
    tree = etree.fromstring(html)
    tag = tree.xpath('//rev')

    for txt in tag:
        textline = txt.text #stringを持ってくる

        textline = textline.replace('[[','')
        textline = textline.replace(']]','')
        textline = textline.replace('{{','{')
        textline = textline.replace('}}','}')
        textline = textline.replace('<!--','')
        textline = textline.replace('-->','')
        textline = textline.replace('<ref>',' <詳細>')
        textline = textline.replace('</ref>',' ')
        textline = textline.replace(' ','')
        textline = textline.replace('http://',' http://')

        f.write(textline.encode('utf_8'))
        pass
    f.close()


    #さらに解析
    f = open('today_py_tmp', 'rb')
    f_lines = f.readlines()
    f.close()
    os.remove('today_py_tmp') #tmpファイルは削除

    r = open(argv, 'wb')
    for line in f_lines:
        #タイトルの摘出
        if re.search(r'== +\S+ ==', line.decode('utf-8')):
            if not(re.search('出典', line.decode('utf-8')) or re.search('関連項目', line.decode('utf-8'))
                or re.search('脚注', line.decode('utf-8')) or re.search('注釈', line.decode('utf-8'))):
                r.write(line)
                pass
            pass

        #何があったかの摘出
        elif line.decode('utf-8').startswith('*'):
            r.write(line)
            pass
        pass
        r.close()
    pass


if __name__ == '__main__':
    #テキトーに作ったお試しのもの
    argv = sys.argv
    argc = len(argv)

    if argc == 2:
        tmp = argv[1]
        main(argv[1])
        pass
    else:
        main(None)
        pass

改めて今日はなんの日かを持ってきてくれるbotを再始動 http://twitter.com/momijinn_raspi