ラベル Python の投稿を表示しています。 すべての投稿を表示
ラベル Python の投稿を表示しています。 すべての投稿を表示

2010年8月7日土曜日

eclipseでpython

eclipseの記事を見てたらPyDevを使えばeclipseでPythonできるとのこと。

http://pydev.org/index.html


eclipseを起動する
ヘルプ→新規ソフトウェアのインストールで「http://pydev.org/updates」を登録
自動的にPyDevがインストールされる
ウィンドウ→設定でPydevを選択、「Auto Config」でインストールされているPythonが自動で登録される、OK。これで準備完了。
ファイル→新規→プロジェクト、Pydev→Pydevプロジェクトを選択すると自動的にPythonのプロジェクトが作成される
srcで右クリック、新規→Pydevモジュール でモジュールファイルが作成される試しにPython2.6にインストールしてあるPybelを使ったソースを入れてみるとちゃんと補完されるし、smilesを読み込んで分子量も計算できる。
PythonのIDEとして使えるかもしんない。

2010年8月2日月曜日

Python sqlite3を使う

import os, sqlite3

def regist():
    con = sqlite3.connect("data.db")    # 通常
    #con = sqlite3.connect('temp.db', isolation_level=None)  # 自動コミット
    #con = sqlite3.connect(":memory:")   #メモリーDB

    # テーブルを作成
    sql = u"""
create table 社員 (
  名前 varchar(10),
  年齢 integer,
  部署 varchar(200)
);
"""
    try:
        # Tableを作成
        con.execute(sql)

        # SQL
        sql = u"insert into 社員 values ('橋本', 26, '広報部')"
        con.execute(sql)
        con.commit()
        # SQL
        sql = u"insert into 社員 values (?, ?, ?)"
        con.execute(sql, (u"小泉", 35, u"営業部"))
        con.execute(sql, (u"亀井", 40, u"営業部"))
        con.commit()
        # SQL
        con.executemany(u"insert into 社員 values (?, ?, ?)",
                    [(u"堀", 44, u"営業部"),
                     (u"鈴木", 23, u"営業部")])
        con.commit()
    finally:
        con.close()
def retrieve():
    con = sqlite3.connect("data.db")    # 通常
    c = con.cursor()
    c.execute(u"select * from 社員")
    print "---------------"
    for row in c: # rowはtuple
        print row[0], row[1], row[2]

def main():
    regist()
    retrieve()
if __name__ == '__main__':
    main()

2010年8月1日日曜日

Pythonでシリアライズ

ちょっとした設定や計算の途中結果を一時保存するには便利な環境。


■marshalを使う


import os,marshal

def writedump():
    data1 = range(1,100,2)
    data2 = ['hori','suzuki','yamada']
    with open('datafile.dat','wb') as outfile:
        marshal.dump(data1,outfile)
        marshal.dump(data2,outfile)
def readdump():
    with open('datafile.dat','rb') as infile:
        print "1:" + str(marshal.load(infile))
        print "2:" + str(marshal.load(infile))
def main():
    writedump():
    readdump()

if __name__ == '__main__':
    main()


■cPickleを使う


import os,cPickle

def writedump():
    data1 = '0'*100000
    data2 = ['hori','suzuki','yamada']
    with open('datafile_pickle.dat','wb') as outfile:
        cPickle.dump(obj = data1,file = outfile, protocol = 2)
        cPickle.dump(obj = data2,file = outfile, protocol = 2)
def readdump():
    with open('datafile_pickle.dat','rb') as infile:
        print "1:" + str(cPickle.load(infile))
        print "2:" + str(cPickle.load(infile))
def main():
    writedump()
    readdump()

if __name__ == '__main__':
    main()

■さらにZip圧縮する


import os,cPickle,gzip

def writedump():
    data1 = '0'*100000
    data2 = ['hori','suzuki','yamada']
    outfile = gzip.open('datafile_pickle_zip.zip','wb')
    cPickle.dump(obj = data1,file = outfile, protocol = 2)
    cPickle.dump(obj = data2,file = outfile, protocol = 2)
    outfile.close()
def readdump():
    infile = gzip.open('datafile_pickle_zip.zip','rb')
    print "1:" + str(cPickle.load(infile))
    print "2:" + str(cPickle.load(infile))
    infile.close()
def main():
    writedump()
    readdump()

if __name__ == '__main__':
    main()




2010年6月20日日曜日

matplotlib

matplotlibはPythondeグラフが使えるようになるモジュール。

まずはnumpyを入れる。

easy_install numpy

インストール時にかなりのエラーがでるが、無視。

http://matplotlib.sourceforge.net/index.html
https://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-0.99.3/

からインストーラーをダウンロードしてインストール。

サンプルはhttp://matplotlib.sourceforge.net/gallery.html#にいっぱいあるし。
楽しいね。



2010年3月10日水曜日

Python本

師匠のおすすめの本を買った。


すでに「ポケットリファレンス」をだいたい読んだ後なので復習的な感じですな。


2010年3月9日火曜日

Python csvファイルをtextファイルに変換する

こんな感じかな


# import modules
import os.path
import csv


# functions
def csv2txt(inFilePath, outFilePath):
    """csv2txt convert csv file to text file.
       Convert comma to tab."""
    # file exists check
    if not os.path.isfile(inFilePath):
        print inFilePath + " is not exist."
        return
    # file extension check
    root, ext = os.path.splitext(inFilePath)
    if ext != ".csv":
        print filepath + " is not .csv."
        return
    root, ext = os.path.splitext(outFilePath)
    if ext != ".txt":
        print filepath + " is not .txt."
        return
    # create output file
    f = open(outFilePath,'w')
    # read csv
    reader = csv.reader(file(inFilePath, 'r'))
    for row in reader:
        newline = "\t".join(row)
        f.write(newline + '\n')
    f.close()

readerにclose()がなかった。自動的に開放されるみたい。

2010年3月8日月曜日

Python 亡記録2題

■ディレクトリ
作業ディレクトリーを変更する
import os
os.chdir(パス名)
現在の作業ディレクトリーを確認する
os.getcwd()


■for関連
2つのシーケンスを同時に回す
a = [1,2,3]
b = [4,5,6,7]
for x, y in zip(a,b):
    print x, y
1 4
2 5
3 6

シーケンスでインデックスと同時に要素を取り出す
a = [5,6,7,8,9]
for i, x in enumerate(a):
    print i, x
0 5
1 6
2 7
3 8
4 9

いつも忘れちゃうんだよな。歳だな。

2010年3月6日土曜日

Python リストのソート2

最初の要素は昇順、2番目の要素は降順

>>> score1 = [2,2,1,1,1,4,4,4]
>>> score2 = [3,4,4,2,1,1,2,2,]
>>> score = zip(score1,score2)
>>> sorted(score,key=lambda x:(x[0],-x[1]),reverse=False)
[(1, 4), (1, 2), (1, 1), (2, 4), (2, 3), (4, 2), (4, 2), (4, 1)]

ほほう

Python リストのソート

>>> name
['yamada', 'suzuki', 'yokoyama', 'takai', 'kashiwagi']
>>> old
[45, 21, 78, 16, 56]
>>> height
[166, 176, 170, 155, 149]
>>> weight
[78, 67, 82, 66, 53]
>>> country
['USA', 'Japan', 'Canada', 'Korea', 'UK']
>>> db = zip(name,old,height,weight,country)
>>> sorted(db,key=lambda x:(x[0],x[1]),reverse=False)
[('kashiwagi', 56, 149, 53, 'UK'), ('suzuki', 21, 176, 67, 'Japan'), ('takai', 1
6, 155, 66, 'Korea'), ('yamada', 45, 166, 78, 'USA'), ('yokoyama', 78, 170, 82,
'Canada')]

ほう

Python リストの抽出

Pythonではリストの抽出にスライスに
リスト[開始位置:終了位置]
という構文を使うが、なんか慣れない。


>>> a = [0,1,2,3,4,5]
>>> a[0:3]
[0, 1, 2]

終了位置の値は返さないらしい。

なんか違和感を覚えてしまう。

2010年2月27日土曜日

PythonでOpenBabelを使う ~Pybelを使う

PybelはOpenBabelの様々なクラス・メソッドの中でよく使う物をPython用に定義したお便利環境です。

詳細は
http://openbabel.org/wiki/Using_OpenBabel_from_Python#Pybel
http://openbabel.org/pybel.html

例えばSDファイルを読み込んでMolに変換して構造を表示するのは簡単。


from pybel import *


inSdFilePath = "test.sdf"
mols = readfile("sdf", inSdFilePath)
for mol in mols:
    mol.make3D()
    mol.draw()      #OASAがインストールされていれば構造を表示する

PythonでOpenBabelを使う ~SDファイル

とりあえず基本的なやつ。

openbabeltest.py
# coding: shift-jis

from openbabel import *

def ReadSdFile(inSdFilePath="test.sdf"):
    #inSdFilePath = "test.sdf"
    conv = OBConversion()
    answer = conv.SetInAndOutFormats("sdf","can")
    mol  = OBMol()
    end_flag = conv.ReadFile(mol,inSdFilePath)
    smiles = []
    while end_flag:
        smile = conv.WriteString(mol).split('\t')[0]    # Smiles文字のみをSplitする
        smiles.append(smile)
        answer = mol.Clear()
        end_flag = conv.Read(mol)
    return smiles
    
# main
smilesStrigList = ReadSdFile()
for smiles in smilesStrigList:
    print smiles

コマンドプロンプト
I:\Python>python openbabeltest.py
ClCC(=O)NC1=C(SCC1)C(=O)OC
COC(=O)C1=C(CCS1)NC(=O)c1ccccc1
COC(=O)C1=C(CCS1)NC(=O)c1cccc(C)c1
COC(=O)C1=C(CCS1)NC(=O)c1ccccc1Cl
COC(=O)C1=C(CCS1)NC(=O)c1ccc(C)c(C)c1

PythonでOpenBabelを使う

TIBCO Spotfire3.1が欧米でリリースされ、日本国内でも近々リリースされると思います。

今回のリリースでの目玉はTextView上でのスクリプトの実行が可能になり、ガイドっぽいことができるようになるのとHeatMapのサポート、Bar&LineChartなどいろいろありますが(詳細)、地味ですがIronPythonのScriptのサポートがあります。

これを機にちょっとPythonを勉強しておこうと思って、環境を作ります。詳細はこちら

  1. Python2.6をインストール http://www.python.org/download/
    • 最新版は3.1なのですがOpenBabelで構造表示に使うPILとOASAが2.6までしか対応していないので。
  2. Pythonのパスを設定
  3. OpenBabel GUIをインストール
  4. OpenBabelのパスを通す
    1. PATHにI:\Program Files\OpenBabel-2.2.3を追加
  5. 環境変数「BABEL_DATADIR」をセット
    1. 例えば、set BABEL_DATADIR=I:\Program Files\OpenBabel-2.2.3な感じ
  6. OpenBabel Python bindingsをインストール
    1. PILとOASAをインストール、いずれもPython2.6用を入れます
    2. OpenBabelのWebにあるテストスクリプトを動かしてみる
    テストスクリプトのうち「mol.make3D()」を実行してみて、
    ==============================
    *** Open Babel Error  in OpenBabel::OBForceFieldMMFF94::ParseParamFile
      Cannot open parameter file
    こんなエラーが出る場合は、環境変数のBABEL_DATADIRが正しくセットされていない時です。コマンドプロンプトでecho %BABEL_DATADIR%とやってみてOpenBabelのGUIのインストールフォルダーが出ることを確認しましょう。