2008/06/01

PyAWSでAmzonの商品を検索

PythonをからAmazon ECSを使ってAmazonの商品情報を検索する場合、PyAWSを使えば簡単に商品情報を取得することができます。

PyAWS

下記にサンプルを掲載いたします。


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import codecs

from pyaws import ecs

sys.stdout = codecs.getwriter('cp932')(sys.stdout)

ACCESS_KEY = "XXXXXXXXXXXXXXXXXXXXX"
LOCALE = "jp"

ecs.setLicenseKey(ACCESS_KEY)
ecs.setLocale(LOCALE)

bags = ecs.ItemSearch(
'Python',
SearchIndex='Books',
ItemPage=0,
ResponseGroup='Request,Small,Images'
)

for bag in bags:
print bag.Title


Amazon ECSを利用するためにはAccess Key IDを取得する必要があります。
Access Key IDの取得方法は下記を参照ください。

Access Key IDの取得

ラベル:

2008/02/24

Python2.5のwith文

Python2.5からwith文が導入されました。with文を使用すればtry文のfinally節で行っていた後処理が明快に記述できます。

例えばファイルを開いてデータを読み出してからクローズする場合は下記のようになります。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import with_statement

# try finallyを使用
try:
file = open(r"C:\test.txt", "r")
for line in file:
print line
finally:
file.close()

# withを使用
with open(r"C:\test.txt", "r") as file:
for line in file:
print line


今回、MySQLに接続してクエリを実行してから接続を閉じる処理をwith文で作成してみたので掲載したいと思います。


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import with_statement

import MySQLdb

class MySQLConnector(object):

def __init__(self, username, password):
self.username = username
self.password = password

def __enter__(self):
self.connection = MySQLdb.connect(db="test", host="localhost", port=3306, user=self.username, passwd=self.password)
self.cursor = self.connection.cursor()
print "called __enter__"
return self.cursor

def __exit__(self, type, value, tb):
self.cursor.close()
self.connection.close()
print "called __exit__"


if __name__ == '__main__':

with MySQLConnector("testuser", "testpassword") as cursor:
cursor.execute("select * from testdata")
for row in cursor.fetchall():
print row



上記のサンプルを説明すると、with文は最初に「__enter__」メソッドを呼び出し、with文から抜け出すときに「__exit__」メソッドを呼び出します。
「__enter__」メソッドの戻り値がwith文の変数(上記のサンプルでは「as cursor」の部分です)に代入されるようです。

※with文の中で例外が発生した場合でも「__exit__」メソッドが呼び出されます。

ラベル:

2008/02/20

BeautifulSoupである属性が存在する要素を抽出

BeautifulSoupである属性が存在する要素を抽出するには、findAllメソッドにキーワード引数を渡して使用するようです。具体的にはキーワード引数名に捜したい属性名を、値にTrueを設定してfindAllメソッドを呼び出します。

例えば「href属性」が存在する要素を取得する場合は下記のようになります。


soup.findAll(href=True)


となります。
簡単ですが、サンプルを作成したので掲載します。


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import codecs
import re

from BeautifulSoup import BeautifulSoup
from BeautifulSoup import NavigableString
from BeautifulSoup import Tag

sys.stdout = codecs.getwriter('cp932')(sys.stdout)

html = """
<div>
<a href="http://www.google.com/" onclick="testMethod1">Google</a>
<a href="http://www.yahoo.co.jp/" onclick="testMethod2">Yahoo! Japan</a>
<a href="http://www.r-stone.net/" onblur="testMethod3">RiverStone</a>
</div>

"""

soup = BeautifulSoup(html)

for tag in soup.findAll(onclick=True):
print tag


上記のプログラムを実行すると、コンソールに下記のメッセージが表示されます。

<a href="http://www.google.com/" onclick="testMethod1">Google</a>
<a href="http://www.yahoo.co.jp/" onclick="testMethod2">Yahoo! Japan</a>

ラベル:

2008/02/18

StringIO

Javaでいうと「StringReader」のようなクラスが必要になりPythonのドキュメントを見るとStringIOというクラスがありました。

StringIOはファイルオブジェクトのメソッドと属性を備えるクラスで、データをファイルではなくメモリ上に持ちます。

簡単なサンプルを作成したので、下記に掲載します。


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import codecs

from StringIO import StringIO

sys.stdout = codecs.getwriter('cp932')(sys.stdout)

buffer = StringIO("")
buffer.writelines(u"あいうえお\n")
buffer.writelines(u"かきくけこ\n")

print buffer.getvalue()
buffer.close()

buffer = StringIO(u"さしすせそ\nたちつてと\n")

for line in buffer:
print line.strip()

buffer.close()

上記のプログラムを実行すると・・・

あいうえお
かきくけこ

さしすせそ
たちつてと

と表示されます。
StringIOよりも高速なcStringIOというクラスがあるようですが、Unicodeをサポートしないようです。

ラベル:

2008/02/17

PyAMFを使ってみた

PyAMFを使用すればPythonとActionScript3とのデータのやりとりをオブジェクトで行うことができます。PyAMFはDjango・Pylons・CherryPyなどのWebフレームワークに対応しています。

今回はDjangoとFlex2の間でデータを送受信する簡単なサンプルを作成しました。
まずはFlex2ですが「NetConnection」クラスを使用してDjangoにデータを送信します。

■PyAMF.mxml


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" applicationComplete="applicationCompleteHandle()">

<mx:Script>
<![CDATA[

public function applicationCompleteHandle():void
{

var netConnection:NetConnection = new NetConnection();
netConnection.connect("http://localhost:8080/pyamf/");

var p:Person = new Person();
p.name = "山田 太郎"
p.age = 28;

var responder:Responder = new Responder(onResult, onError);
netConnection.call("greeting", responder, "Hello PyAMF", p)
}


private function onResult(result:*):void
{
trace(result)
}

private function onError(error:*):void
{
trace(error)
}

]]>
</mx:Script>

</mx:Application>




■Person.as

package
{
public class Person
{

public var name:String;
public var age:int;

}
}


続いてDjango側は「pyamf.remoting.djangogateway.DjangoGateway」クラスを使用してFlex2とのデータを送受信します。
views.pyなどにDjangoGatewayを定義してDjangoGatewayのコンストラクタに公開したいメソッドの名称とメソッド自身を辞書に格納して渡します。


def greeting(request, message, person):
print message
print person.name.encode("cp932")
return "Hello Flex2"

gw = DjangoGateway({'greeting':greeting})


あとはurls.pyで上記の「gw」が呼び出されるように設定します。(greetingメソッドを直接呼び出すわけではありません)

from django.conf.urls.defaults import *

urlpatterns = patterns('',
(r'^pyamf/', 'rstone.moblogger.views.gw'),
)


上記のプログラムを実行するとDjangoでは・・・

Hello PyAMF
山田 太郎

と表示され、Flex2では・・・

Hello Flex2

と表示されました。
Flex2からDjangoに送信したPersonクラスですが、Djangoでは「pyamf.ASObject」になるようです。

ラベル: ,

2008/02/16

Pythonで全角から半角への変換

Pythonで全角カナを半角カナに変換したくて、そのようなモジュールがあるかWebで調べたところ・・・

見つかりました。
zenhan.pyというモジュールで下記のブログで公開されているようです。

blogSetomits zenhan.py0.4


早速、ダウンロードして使ってみました。このモジュールでは「半角→全角」と「全角→半角」に変換できるようです。

下記に簡単なサンプルを掲載します。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import codecs
import zenhan

sys.stdout = codecs.getwriter('cp932')(sys.stdout)

s1 = u"アイウエオ1234567890ABCDEF@"
s2 = u"アイウエオ1234567890abcdef@"

# 半角から全角に変換
print zenhan.z2h(s1)

# ASCIIとカナだけ変換したい場合
print zenhan.z2h(s1, zenhan.ASCII|zenhan.KANA)

# ASCIIと数字だけ変換したい場合
print zenhan.z2h(s1, zenhan.ASCII|zenhan.DIGIT)

# 数字だけ変換したい場合
print zenhan.z2h(s1, zenhan.DIGIT)

# ASCIIだけ変換したい場合
print zenhan.z2h(s1, zenhan.ASCII)

# 半角から全角に変換
print zenhan.h2z(s2)


■実行結果

アイウエオ1234567890ABCDEF@
アイウエオ1234567890ABCDEF@
アイウエオ1234567890ABCDEF@
アイウエオ1234567890ABCDEF@
アイウエオ1234567890ABCDEF@
アイウエオ1234567890abcdef@

ラベル:

2008/02/15

Pythonで「~」をエンコードすると例外が発生

Pythonで「~」をSJISやEUCにエンコードすると例外が発生します。

※cp932やmbcsを使用すれば例外は発生しません。

■検証したコード

#!/usr/bin/env python
# -*- coding: utf-8 -*-

s = u"~"

try:
s.encode("shift_jis")
print "shift_jis ok"
except UnicodeEncodeError, e:
print e

try:
s.encode("shift_jis_2004")
print "shift_jis_2004 ok"
except UnicodeEncodeError, e:
print e

try:
s.encode("shift_jisx0213")
print "shift_jisx0213 ok"
except UnicodeEncodeError, e:
print e

try:
s.encode("euc_jp")
print "euc_jp ok"
except UnicodeEncodeError, e:
print e

try:
s.encode("utf8")
print "utf8 ok"
except UnicodeEncodeError, e:
print e


上記のプログラムを実行すると・・・

'shift_jis' codec can't encode character u'\uff5e' in position 0: illegal multibyte sequence
'shift_jis_2004' codec can't encode character u'\uff5e' in position 0: illegal multibyte sequence
'shift_jisx0213' codec can't encode character u'\uff5e' in position 0: illegal multibyte sequence
'euc_jp' codec can't encode character u'\uff5e' in position 0: illegal multibyte sequence
utf8 ok

と表示されます。

文字コード「U+FF5E」を文字コード表で見てみると・・・


Fullwidth Tildeとなっており、さらにWebで調べるとWindowsの問題のようです。

WAVE DASH - FULLWIDTH TILDE問題

これはFullwidth TildeをWave Dashに変換すれば解決できるようです。


下記に修正したプログラムと出力結果を掲載します。


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import string

s = u"~"
s = string.replace(s, u'\uff5e', u'\u301c')

try:
s.encode("shift_jis")
print "shift_jis ok"
except UnicodeEncodeError, e:
print e

try:
s.encode("shift_jis_2004")
print "shift_jis_2004 ok"
except UnicodeEncodeError, e:
print e

try:
s.encode("shift_jisx0213")
print "shift_jisx0213 ok"
except UnicodeEncodeError, e:
print e

try:
s.encode("euc_jp")
print "euc_jp ok"
except UnicodeEncodeError, e:
print e

try:
s.encode("utf8")
print "utf8 ok"
except UnicodeEncodeError, e:
print e


shift_jis ok
shift_jis_2004 ok
shift_jisx0213 ok
euc_jp ok
utf8 ok

ラベル:

2008/02/14

codecsで使えるエンコーディング

Pythonのcodecsで使用できるエンコーディングは「encodings」モジュールにあるようです。どこにあるのか気になってはいたのですが、偶然に見つけることができました。

私の環境(WindowsXP)では「C:\Python25\Lib\encodings」になります。

SJISだけでも・・・

・shift_jis
・shift_jis_2004
・shift_jisx0213

何種類かあるようです。

ラベル:

2008/02/13

BeautifulSoupを使って要素を追加する

BeautifulSoupを使ってHTMLに要素を追加する機会があったのでサンプルを掲載します。BeautifulSoupでは要素をTagクラスとして扱うので、要素を追加する場合はTagクラスのインスタンスを生成して、親となる要素(Tagクラス)の「insert」メソッドで追加することができます。
また、要素にテキストを追加したい場合は「NavigableStringクラス」を使用すれば追加できるようです。

下記が簡単なサンプルです。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import codecs

from BeautifulSoup import BeautifulSoup
from BeautifulSoup import NavigableString
from BeautifulSoup import Tag

sys.stdout = codecs.getwriter('cp932')(sys.stdout)

html = """
<div>
<a href="http://www.google.com/">Google</a>
<a href="http://www.yahoo.co.jp/">Yahoo! Japan</a>
</div>

"""

soup = BeautifulSoup(html)

tag = Tag(soup, "a")
tag["href"] = "http://www.r-stone.net/"
text = NavigableString("リバーストーン")
tag.insert(0, text)

soup.div.insert(0, tag)

print soup.prettify()



このプログラムを実行すると



<div>
<a href="http://www.r-stone.net/">
リバーストーン
</a>
<a href="http://www.google.com/">
Google
</a>
<a href="http://www.yahoo.co.jp/">
Yahoo! Japan
</a>
</div>




と表示され、正常に要素が追加されているようです。

ラベル:

2008/02/11

Last.fmのAPI

Last.fm API に「あるアーティストと関係の深いアーティストを取得」するAPIがあります。そのAPIをPythonから使用するサンプルを作成しました。

データ形式としてプレインテキストとXMLに対応しているようです。


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from urllib import urlopen

try:
from xml.etree import ElementTree
except:
from elementtree import ElementTree

def create_url(artist):
return "http://ws.audioscrobbler.com/1.0/artist/%s/similar.xml" % artist


data = urlopen(create_url("beatles")).read()
print data
etree = ElementTree.fromstring(data)

for index, tag in enumerate(etree.getiterator("artist")):
print (index + 1), tag.find("name").text


上記のプログラムを実行すると「Beatles」との関係が深いアーティストが100件表示されます。

■実行結果(上位20件)

1 John Lennon
2 The Rolling Stones
3 Led Zeppelin
4 The Who
5 Paul McCartney
6 Pink Floyd
7 The Beach Boys
8 George Harrison
9 The Doors
10 David Bowie
11 Simon & Garfunkel
12 Jimi Hendrix
13 The Kinks
14 Queen
15 The Velvet Underground
16 Cream
17 Oasis
18 Coldplay
19 Paul McCartney & Wings
20 Franz Ferdinand

ラベル:

2008/02/10

PILを使ってWeb上の画像を読み込む

PythonのPIL(Python Imaging Library)を使用してWeb上の画像を読み込む必要があったので、簡単なサンプルを作成しました。


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import Image
import urllib

from cStringIO import StringIO

buffer = urllib.urlopen("http://www.r-stone.net/blogs/satoshi/uploaded_images/blog2008020901-705040.jpg").read()
image = Image.open(StringIO(buffer))

image.thumbnail([100, 100])
image.save(r"c:\test.jpg")

ラベル:

2008/02/08

BeautifulSoupを使ってHTMLを解析

PythonでHTMLを解析してHTMLのタグをいろいろ操作する必要があり、調べてみると「BeautifulSoup」という便利なモジュールがありました。

BeautifulSoup

早速使ってみましたが、これはすごく良いですね。簡単にHTMLを解析して操作することができました。しかも、HTMLだけではなくXMLにも使えるようです。

EasyInstallに対応しているので、下記のコマンドで簡単にインストールすることができました。

easy_install beautifulsoup

下記に簡単なサンプルを掲載します。

■HTML内の特定のタグを取得

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from BeautifulSoup import BeautifulSoup
from BeautifulSoup import Tag

html = """
<ul>
<li><a href="aaa.html">aaa</a></li><p>
<li><a href="bbb.html">bbb</a></li>
</ul>

"""

soup = BeautifulSoup(html)

# aタグを取得
for tag in soup.findAll('a'):
print tag


■出力結果

aaa
bbb


■タグを削除(Tagクラスのextractメソッドを使用)

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from BeautifulSoup import BeautifulSoup
from BeautifulSoup import Tag

html = """
<ul>
<li><a href="aaa.html">aaa</a></li><p>
<li><a href="bbb.html">bbb</a></li>
</ul>

"""

soup = BeautifulSoup(html)

#print soup.prettify()

# aタグを取得
for tag in soup.findAll('a'):
tag.extract()

print soup.prettify()


■出力結果

<ul>
<li>
</li>
<p>
</p>
<li>
</li>
</ul>


■タグを別のタグで置き換える

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from BeautifulSoup import BeautifulSoup
from BeautifulSoup import Tag

html = """
<ul>
<li><a href="aaa.html">aaa</a></li><p>
<li><a href="bbb.html">bbb</a></li>
</ul>

"""

soup = BeautifulSoup(html)

#print soup.prettify()

# aタグを取得
for tag in soup.findAll('a'):
t = Tag(soup, "foo")
tag.replaceWith(t)


■出力結果

<ul>
<li>
<foo>
</foo>
</li>
<p>
</p>
<li>
<foo>
</foo>
</li>
</ul>

ラベル:

2008/02/07

Pythonの書籍

Pythonの勉強をするために何冊か本を購入しました。私がよく参考にする本は下記の4冊です。

Pythonチュートリアル
初めてのPython 第2版
Python クックブック 第2版
Pythonクィックリファレンス

仕事などでプログラムの経験がある場合は上記の4冊があれば、一通り勉強できると思います。
読み進める順番は・・・

1. 初めてのPython
2. Pythonチュートリアル
3. WebでPython2.5の勉強
4. Pythonクィックリファレンス
5. Pythonクックブック

がおすすめです。
また、プログラムの経験が浅い場合は下記の書籍が参考になると思います。

Pythonで学ぶプログラム作法
みんなのPython
実践Python~文字列操作からWebアプリケーション開発まで

私は読んだことがありませんが、入門書として下記の書籍もあるようです。

はじめてのPython―「生産性」「汎用性」に優れ、習得が容易なプログラミング言語 (I/O BOOKS)
速効!Pythonプログラミング―バージョン2.5対応

ラベル: ,

2008/02/06

DjangoのテンプレートでHTMLを出力

Djangoのテンプレートで直接HTMLを出力する必要があり、テンプレートのパラメータにHTMLを格納して出力したところタグがエスケープされてしまいました。

原因を調べたところ、「django.template.Context」クラスのコンストラクタのパラメータ「autoescape」がデフォルトでTrueになっているようです。

今まではショートカット「render_to_response」を使ってレスポンスを生成していましたが、下記のようにプログラムを変更して対応しました。


t = loader.get_template('post.html')
c = Context({'html':html}, False)
return HttpResponse(t.render(c))

Contextのコンストラクタの第2引数にFlaseを渡すのがポイントです。

ラベル: , ,

2008/02/05

PyDevでDjangoのアプリをデバッグする

EclipseのPyDevを使用すればDjangoを使用して作成したWebアプリケーションをデバッグすることができます。簡単ですが下記に手順をメモします。

[環境]
Windows XP
Eclipse3.3.1
Python2.5
Django0.97

1. コマンドプロンプトでEclipseのワークスペース直下に移動してプロジェクトを作成



2. EclipseにてPyDevのプロジェクトを作成する



プロジェクト名には「1」で作成したプロジェクトと同じ名前を入力し、プロジェクトタイプの選択を「Python2.5」に設定して「デフォルトのsrc…」のチェックをはずす。



3. コマンドプロンプトで「DjangoDebugSiteプロジェクト」直下に移動してアプリケーションを作成


4. EclipseのPyDevプロジェクトをPYTHONPATHに追加

「2」で作成したプロジェクトを右クリック->プロパティ->「PyDev -PYTHONPATH」->「ソースフォルダの追加」にてプロジェクトをPYTHONPATHに追加する



5. 動作可能なDjangoのアプリケーションを作成(適当に動作可能なプログラムを作成してください)


6. デバッグの構成を作成するためにmanage.pyをデバッグで起動

デバッグの構成を作成するためにmanage.pyをデバッグで起動します。(エラーが表示され起動しませんが問題はありません)


7. デバッグの構成を修正
「メニュー」->「実行」->「デバッグダイアログを開く」を選択してデバッグの構成を開くと、先ほど起動に失敗したデバッグの構成があります。



引数のタブを選択して、プログラムの引数に「runserver 8080 --noreload」と設定します。


8. あとはプログラムにブレイクポイントを設定してからデバッグで起動し、ブラウザからアクセスすればブレイクポイントで止まります。


やはり、ステップインを使ってデバッグが行えると開発するのが楽ですね。
開発効率が上がること間違いなしです。

ラベル: , , ,

2008/02/04

Pythonで現在の日付を取得してフォーマットする

Javaでは「java.util.Date」クラスを引数なしのコンストラクタで生成すれば現在の時刻が設定されます。また、日付をフォーマットしたい場合は「java.text.SimpleDateFormat」クラスなどを使用すると思います。

Pythonで現在の時刻を取得するには「datetimeクラス」の「nowメソッド」や「todayメソッド」を使用するようです。nowメソッド・todayメソッドの戻り値はdatetimeクラスとなっており、フォーマットしたい場合は「strftimeメソッド」に書式化文字列を引数として渡して呼び出します。

下記に簡単なサンプルを掲載します。


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import codecs
from datetime import datetime

sys.stdout = codecs.getwriter('cp932')(sys.stdout)

now = datetime.now()
today = datetime.today()

print now.__class__
print today.__class__

print now.strftime("現在の時刻は %Y年%m月%d日 %H時%M時%S秒 です。")
print today.strftime("現在の時刻は %Y年%m月%d日 %H時%M時%S秒 です。")


このプログラムを実行すると、私の環境ではコンソールに下記の文字列が表示されました。


<type 'datetime.datetime'>
<type 'datetime.datetime'>
現在の時刻は 2008年02月04日 21時46時08秒 です。
現在の時刻は 2008年02月04日 21時46時08秒 です。

ラベル:

2008/01/31

Pythonのfor文

Pythonのfor文はC言語・Javaなどのように、繰り返し数を指定したループカウンタは使えません。もしループ内でループのインデックスを使う必要がある場合はenumerate関数を使用します。


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import codecs

sys.stdout = codecs.getwriter('cp932')(sys.stdout)

names = [u"太郎", u"次郎", u"三郎"]

# 通常のループ
for name in names:
print name

# インデックスを取得するループ
for index, name in enumerate(names):
print index, name

このプログラムを実行すると・・・


太郎
次郎
三郎
0 太郎
1 次郎
2 三郎


と表示されます。私は初めてPythonでプログラムを作成したとき、ループ内でインデックスを取得する方法がわからなく悩みました。

ラベル:

2008/01/30

Pythonで月のカレンダーを行列で取得

Pythonで月のカレンダーを行列で取得するにはcalendarモジュールのmonthcalendar関数を使用します。デフォルトでは月曜日から始まる月のカレンダーの行列を取得できるようです。


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from calendar import monthcalendar

month_calendar = monthcalendar(2008, 1)

for week in month_calendar:
print week


上記のプログラムを実行すると・・・



[0, 1, 2, 3, 4, 5, 6]
[7, 8, 9, 10, 11, 12, 13]
[14, 15, 16, 17, 18, 19, 20]
[21, 22, 23, 24, 25, 26, 27]
[28, 29, 30, 31, 0, 0, 0]



と表示されます。
2008年の1月は火曜日から始まるので最初の週の先頭は0となっています。
週の最初の曜日を変更したい場合はcalendarモジュールのfirstweekday関数を使用してください。

例えば、週の最初を日曜日にしたい場合は


import calendar
calendar.setfirstweekday(calendar.SUNDAY)


と設定すればOKです。

ラベル:

2008/01/29

Pythonで文字列のエンコードを判定する

プログラムを作成していて、文字列のエンコードを判定する必要があり、いろいろ調べると・・・

chardetモジュールを使えば簡単に文字列のエンコードを判定することができるようです。chardetモジュールは標準モジュールに含まれないので別途インストールする必要があり、easy_installでインストールしました。

easy_install chardet

エンコードを判定する簡単なサンプルを作成したので、下記に掲載します。



#!/usr/bin/env python
# -*- coding: utf-8 -*-

import chardet

print chardet.detect(u"あいうえお".encode("utf8"))
print chardet.detect(u"あいうえお".encode("euc-jp"))
print chardet.detect(u"あいうえお".encode("shift_jis"))
print chardet.detect(u"あいうえお。".encode("shift_jis"))
print chardet.detect(u"あいうえお、".encode("shift_jis"))



上記のプログラムを実行すると・・・


{'confidence': 0.96906250000000005, 'encoding': 'utf-8'}
{'confidence': 0.98999999999999999, 'encoding': 'EUC-JP'}
{'confidence': 0.5, 'encoding': 'windows-1252'}
{'confidence': 0.98999999999999999, 'encoding': 'SHIFT_JIS'}
{'confidence': 0.98999999999999999, 'encoding': 'SHIFT_JIS'}


と表示されました。confidenceは判定の信頼度のようです。
何故かshift_jisは句読点を含まないとうまく判定できていないようです。

ラベル:

2008/01/28

PythonからGoogle Calendarのデータを取得

PythonからGoogle Calendarのデータを取得するサンプルを作成したので掲載します。後日、時間があればGoogle Calendarのデータを操作するサンプルを掲載したいと思います。



#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import codecs
import gdata.calendar.service;

sys.stdout = codecs.getwriter('cp932')(sys.stdout)

SOURCE = "RiverStone"

email = "XXXX"
password = "XXXX"

service = gdata.calendar.service.CalendarService()
service.email = email
service.password = password
service.source = SOURCE
service.ProgrammaticLogin()

feed = service.GetCalendarEventFeed()

for entry in feed.entry:

# タイトル
print entry.title.text

# 日時
for date_and_hour in entry.when:
print date_and_hour.start_time
print date_and_hour.end_time

# 場所
for place in entry.where:
print place.value_string

# 説明
print entry.content.text


ラベル: ,

2008/01/23

PythonからGoogleSpreadsheetを更新する

Pythonから「gdata-python-client」を使用してGoogleSpreadsheetの値を更新することができます。簡単なサンプルを作成いたしましたので下記に掲載します。

※プログラムに定義されている変数に適切な値を設定してください。

_username: GoogleAccountのメールを設定します。
_password: GoogleAccountのパスワードを設定します。
_key: GoogleSpreadsheetにアクセスした際のURLに表示される「key」の値を設定します。


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import codecs
import gdata.spreadsheet.service

sys.stdout = codecs.getwriter('cp932')(sys.stdout)

# GoogleAccountのメール
_username = "xxxxx"

# GoogleAccountのパスワード
_password = "xxxxx"

# SpreadsheetのURLに表示される「key」の値 ccc?key=
_key = "xxxxx"

service = gdata.spreadsheet.service.SpreadsheetsService()
service.email = _username
service.password = _password
service.source = "RiverStone"
service.ProgrammaticLogin()


worksheets = service.GetWorksheetsFeed(_key)
sheet_ids = []

for entry in worksheets.entry:
sheet_ids.append(entry.id.text.split("/")[-1])

for index in range(1, 10):
service.UpdateCell(index, index, str(index * index), _key, sheet_ids[0])

更新対象となるスプレッドシートを開いた状態で上記のプログラムを実行すると、リアルタイムで値が設定されるようです。見ていると面白いですね。

ラベル: ,

2008/01/22

Pythonから最寄りの駅情報を取得する

HeartRailsが提供するWeb APIを使えば、経度・緯度で指定した地点周辺の駅情報を取得できるようです。

今回はPythonからAPIを使用するサンプルを作成いたしましたので掲載します(地点として弊社のある網走市を設定しました)。



#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import codecs
import urllib
import elementtree

sys.stdout = codecs.getwriter('cp932')(sys.stdout)

encoding = "utf-8"
url = "http://express.heartrails.com/api/xml?"

query = {
"method": "getStations",
"x": 144.265305,
"y": 44.019592,
}

url += urllib.urlencode(query)

result = urllib.urlopen(url).read()

print result

上記の他にも「路線情報取得API」や「駅情報取得API」などがあるようです。
詳しくはHeartRailsのサイトをご覧ください。

ラベル: ,

2008/01/21

EclipseでPythonを使う

今まで、Pythonのプログラムを書くときはEmacsのpython-modeを使用していましたが、近頃はEclipseのPythonプラグイン「PyDev」を使用するようになりました。

PyDevを使用すればプログラムにブレイクポイントを設定してデバッグもできるし、プログラムの途中まで入力すれば下の画像のように補完してくれます。



Eclipseに慣れていて、Pythonでプログラムを書く人にはおすすめです。

ラベル: ,

2008/01/20

Pythonからコマンドを実行する

Pythonからコマンドを実行する機会があったのでメモ。
Pythonからコマンドを実行には「osモジュール」の「systemメソッド」を使用する。

下記にサンプルを掲載します。


import os

os.system("dir")

raw_input()

ラベル: ,

2008/01/19

DjangoとTurboGears

最近、PythonのWebアプリケーションフレームワークについていろいろ調べています。
DjangoTurboGearsが良さそうですね。

Djangoの方が日本語の情報が多くて人気があるみたいですが、TurboGearsで使われているテンプレートエンジンのKIDが私好みなんですよね。

ラベル: , ,

2008/01/18

Pythonを使用してBloggerのデータを取得

PythonにはGoogle Data APIのパッケージ(gdata-python-client)が提供されているので比較的簡単にBloggerのデータを取得することができます。

簡単なサンプルを作成したので掲載します。

動作環境として、Pythonのバージョンは2.5、gdata-python-clientのバージョンは「1.0.10.1」を使用します。また、変数「username・password・blogid」は適切な値に置き換えてください。


# -*- coding: utf-8 -*-

try:
from xml.etree import ElementTree # for Python 2.5 users
except:
from elementtree import ElementTree

from gdata import service
from gdata.service import Query
import gdata
import atom
import getopt
import sys
import codecs

sys.stdout = codecs.getwriter('cp932')(sys.stdout)

username = "xxxxxx"
password = "xxxxxx"
blogid = "xxxxxxxxxxxxxxxxxxx"

service = service.GDataService(username, password)
service.source = 'RiverStone'
service.service = 'blogger'
service.server = 'www.blogger.com'
service.ProgrammaticLogin()

query = Query()
query.feed = '/feeds/' + blogid + '/posts/default'
feed = service.Get(query.ToUri())

# ブログのタイトルを出力
print feed.title.text

# 投稿した記事のタイトル・内容・タグを出力
for entry in feed.entry:

print "--------------------------------------"
print "title: " + entry.title.text

tags = ""

for category in entry.category:
print "tag: " + category.term

print unicode(entry.content.text)[0:20]

print "--------------------------------------"


私の環境では、下記のデータが出力されました。

Develogger
--------------------------------------
title: Pythonを使用してBloggerのデータを取得
tag: Python
tag: GoogleDataAPI
PythonにはGoogle Data
--------------------------------------
--------------------------------------
title: Googleの証明書の期限が・・・
tag: Google
今日の昼過ぎにGmailにアクセスしたと
--------------------------------------

ラベル: ,