| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

差分

ナビゲーションに移動 検索に移動
編集の要約なし
==[[Python 標準ライブラリ概観]]==
[[Python]] | [[言語まとめ Python]] | [[Python サンプルコード]] | [[言語まとめ Python]] |
[[Python ライブラリ]] |
*[[Python ]] チュートリアル
**http://www.python.jp/doc/release/tutorial/
*[[Python ]] 標準ライブラリ
**http://www.python.jp/doc/release/library/index.html#library-index
*グローバルモジュールインデクス
**http://www.python.jp/doc/release/modindex.html
*[[Python ライブラリリファレンスライブラリ]]リファレンス
**http://www.python.jp/doc/release/lib/contents.html
*日本Pythonユーザ会(PyJUG)日本[[Python]]ユーザ会(PyJUG)**http://www.python.jp/[[Zope]]/
===OSインターフェース [os]===
>>> import os
>>> os.getcwd()
'C:\\Programs\\Python25[[Python]]25'
=====設定=====
====環境変数の設定====
>>> os.environ["PHRASE_ENV"] = "test"
>>> os.environen[[vi]]ron.get("PHRASE_ENV")
'test'
====現在動いている [[Python ]] モジュールの 絶対パスを取得====
import os
print os.path.abspath(os.path.dirname(__file__))
====ファイルのタイムスタンプを取得ファイルの[[タイムスタンプ]]を取得====
>>> import os
>>> os.stat('test.txt').st_mtime
===ファイルの文字コードファイルの[[文字コード]](codecs)===*文字コードを指定して、ファイルを開く[[文字コード]]を指定して、ファイルを開く
import codecs
fd = codecs.open(search_result_file, 'r', 'utf-8')
'replace': replace malformed data with a suitable replacement marker, such as '?' or '\ufffd'
'ignore': ignore malformed data and continue without further notice
'xmlcharrefreplace': replace with the appropriate [[XML ]] character reference (for encoding only)
'backslashreplace': replace with backslashed escape sequences (for encoding only)
===コマンドライン引数 [sys]===
===正規表現を利用する [re]===
http://www.python.jp/doc/2.5/lib/re-objects.html
http://www.python.jp/[[Zope]]/articles/tips/regex_howto/regex_howto_4====正規表現による文字列の置換[[正規表現]]による文字列の置換====
*sub(pattern, repl, string, count=0, flags=0) を利用する
>>> s = r'AaBbCc'
<blockquote>もしグループが、複数回マッチしたパターンの一部に 含まれていれば、 最後のマッチが返されます。</blockquote>
====正規表現による分割[[正規表現]]による分割====
*re.split を利用
>>> import re
|. が改行も含めて、全ての文字とマッチするように指定する
|-
|IGNORECASEIGNO[[R]]ECASE(I)
|大文字小文字を区別しない
|-
|-
|VERBOSE(X)
|冗長な正規表現(もっと、きれいで分かりやすくまとめられる表現)を有効にする。冗長な[[正規表現]](もっと、きれいで分かりやすくまとめられる表現)を有効にする。
|-
|}
===数学 [math]===
*[[Python 数学]]
>>> import math
>>> pow(2,2)
===URL による任意のリソースへのアクセス[urllib]===
====日本語をURLエンコーディングする日本語をURL[[エンコーディング]]する====
=====例 =====
*マップ型オブジェクト、または 2 つの要素をもったタプルからなるシーケンスを、 "URL U[[R]]L にエンコードされた (url-encoded)" に変換して、urlopen() のオプション引数 data に適した形式にする。
import urllib
===インターネットアクセス [urllib2]===
====指定されたURLを読む指定されたU[[R]]Lを読む====
>>> import urllib2
>>> f = urllib2.urlopen('http://typea.info')
>>> print f.read(100)
<!DOCTYPE [[HTML ]] PUBLIC "-//W3C//DTD [[HTML ]] 4.01 Transitional//EN">
====CGIにデータを送信し結果を得る====
>>> import urllib2
>>> req = urllib2.Request[[R]]equest(url='http://typea.info/tips/wiki.cgi',data='action=RSS[[R]]SS')
>>> f = urllib2.urlopen(req)
>>> print f.read()
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rdf:RDF[[R]]DF
xmlns="http://purl.org/rss/1.0/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
====CGI のサポート (cgi)====
*http://www.python.jp/doc/release/lib/module-cgi.html
====HTMLタグのエスケープ[[HTML]]タグのエスケープ====
>>> from xml.sax.saxutils import escape
>>> escape("<div>")
13777
====[[タイムスタンプ]]====
*[http://ja.wikipedia.org/wiki/ISO_8601 ISO 8601]
>>> from datetime import datetime
'2009-07-29T07:45:05.227000'
====タイムスタンプから、datetime [[タイムスタンプ]]から、datetime オブジェクトを作成====
>>> from datetime import datetime
>>> ts = os.stat(r'/test.txt').st_ctime
===データ圧縮 [zlib]===
>>> import zlib
>>> s = 'Common data archiving archi[[vi]]ng and compression formats are directly supported by
modules including: zlib, gzip, bz2, zipfile, and tarfile. '
>>> len(s)
111
>>> zlib.decompress(t)
'Common data archiving archi[[vi]]ng and compression formats are directly supported by modules
including: zlib, gzip, bz2, zipfile, and tarfile. '
>>> zlib.crc32(s)
(1, 1)
===出力書式===
{{category [[Category:書式}}]]
====reprモジュール [repr]====
*repr モジュールは 巨大で深くネストした内容を簡略表示する、repr() 関数のカスタム版を提供
>>> repr(dir(os))
"['F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX',
'UserDict', 'W_OK', 'X_OK', '_Environ_En[[vi]]ron', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list', '_make_stat_result', '_make_statvfs_result', '_pickle_stat_result', '_pickle_statvfs_result', 'abort', 'access', 'altsep', 'chdir','chmod','lossee','curdiir' defppaath 'devnnuull 'dup'',, 'p222', envvironenv[[vi]]ron, 'errnoo','rroorr','execll','xecclle''execcllp''execcllpe 'execcvv',execcvve''execcvvp''execcvvpe 'extsseep''fdoppeen''fstaatt',fsynncc',getccwwd''getccwwdu 'geteennv''getppiid''isatttty''lineessep 'listtddir 'lseeekk',lstaatt
'maakkedirs 'mkdirr'', ame'',, 'open', 'pardir','ath'',, 'pathsep' pipe'',, 'popen', ppenn22',popeen33',popeen44',puteennv',read'',, 'remove', 'removedis, 'renammme','renamees', 'rmdir', sp',, 'swnnnl','pawnnlle''spawnnvv',spawnnvve''starttffil, 'stat''', 'stat_float_times', 'stat_result', 'statvf
_esulltt', strerroor' sys', ''syemmm', 'empnamm','imes'',, 'tmpfile','mpnamm'', mask'',, 'linkkk', 'nsetennv' urandoomm',utime'',, 'itpiiid','alk',, 'write']"
return l
l = trav('C:\\', 'Python25[[Python]]25')
# 階層構造を持ったリストを出力
====textwrap モジュール [textwrap]====
*textwrap モジュールは、文章の段落を画面幅に合わせるようにフォーマットするモジュールは、[[文章]]の段落を画面幅に合わせるようにフォーマットする
>>> import textwrap
*string モジュールは、Template クラスを含んでいる。
*アプリケーションを変更することなしにカスタマイズできる
*プレイスホルダーの書式は、 $ + Pythonの識別子[[Python]]の識別子
*{}で囲むことで、スペースで区切られていなくても良い
*$$で、$をエスケープする
>>> from string import Template
>>> t = Template('$field_a, $field_b')
>>> d = dict(field_a='FIELD_AF[[IE]]LD_A')
>>> t.substitute(d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python25[[Python]]25\lib\string.py", line 170, in substitute
return self.pattern.sub(convert, self.template)
File "C:\Python25[[Python]]25\lib\string.py", line 160, in convert
val = mapping[named]
KeyError: 'field_b'
>>> t.safe_substitute(d)
'FIELD_AF[[IE]]LD_A, $field_b'
====デリミタのカスタマイズ====
===シリアライズ [pickle]===
====シリアライズする====
Pythonオブジェクトをシリアライズする簡単な例[[Python]]オブジェクトをシリアライズする簡単な例
>>> d = { 'k1':123, 'k2':456, 'k3':789}
>>> d
!書式
!C言語の型
!Pythonの型[[Python]]の型
|-
|x
=====実行結果=====
>python test.py
WARNINGWA[[R]]NING:root:Hello ERRORE[[R]][[R]]O[[R]]:root:logging
====出力は設定可能====
=====mymodule.py=====
import logging
log = logging.getLogger('MyModule')
log.setLevel(logging.WARNWA[[R]]N)
def doSomething():
DEBUG:MyApp:app's debugging log.
INFO:MyApp:app's information log.
WARNINGWA[[R]]NING:MyApp:app's warning log. ERRORE[[R]][[R]]O[[R]]:MyApp:app's error log. WARNINGWA[[R]]NING:MyModule:modlue's warning log. ERRORE[[R]][[R]]O[[R]]:MyModule:modlue's error log.
===XML Dom [xml.dom]===
*構造化マークアップツール
**http://docs.python.jp/3.3/library/markup.html
*xml.dom -- 文書オブジェクトモデル ([[DOM]]) API
**http://docs.python.jp/3.3/library/xml.dom.html
====RSSを解析する[[R]]SSを解析する====
import urllib2
import xml.dom.minidom
*構造化マークアップツール
**http://pythonjp.sourceforge.jp/dev/library/markup.html
*The [[Python ]] Standard Library(The Element Interface)
**http://www.python.org/doc/current/library/xml.etree.elementtree.html?highlight=xml.etree#the-element-interface
*xml.etree.ElementTree ― ElementTree [[XML ]] API
**http://pythonjp.sourceforge.jp/dev/library/xml.etree.elementtree.html
*ElementTree オブジェクト
**http://www.python.jp/doc/release/lib/elementtree-elementtree-objects.html
*XMLの論考: PythonにおけるElementTreeのXMLプロセス[[Python]]におけるElementTreeのXMLプロセス
**http://www.ibm.com/developerworks/jp/xml/library/x-matters28/index.html
====XPathを利用してElementTreeを解析[[XPath]]を利用してElementTreeを解析====*[[Amazon Web Serviceを解析する例Service]]を解析する例
=====例=====
import urllib2
return ElementTree.QName(ns, tag).text
ns = r'http://webserviceswebser[[vi]]ces.amazon.com/AWSECommerceServiceAWSECommerceSer[[vi]]ce/2005-10-05'
# xmlnsが指定されている場合、タグを{xmlnsの値}タグ名 といちいち書く必要があるため、そのように展開したものを保持しておく
# ./{http://webserviceswebser[[vi]]ces.amazon.com/AWSECommerceServiceAWSECommerceSer[[vi]]ce/2005-10-05}ItemAttributes/{http://webserviceswebser[[vi]]ces.amazon.com/AWSECommerceServiceAWSECommerceSer[[vi]]ce/2005-10-05}Title
q_items = './/{0}'.format(qn('Item'))
q_title = './{0}/{1}'.format(qn('ItemAttributes'), qn('Title'))
q_author = './{0}/{1}'.format(qn('ItemAttributes'), qn('Author'))
q_asin = './{0}'.format(qn('ASIN'))
q_url = './{0}'.format(qn('DetailPageURLDetailPageU[[R]]L')) q_img = './{0}/{1}'.format(qn('SmallImage'), qn('URLU[[R]]L'))
# Amazon Product Advertise API リクエスト URLU[[R]]L request = r'http://ecs.amazonaws.jp/onca/xml?AWSAccessKeyIdAWS[[Access]]KeyId=1498TGK1YPN1JATPXXG2&AssociateTag=typea09-22&Keywords=%E6%89%8B%E5%A1%9A%E3%80%80%E6%B2%BB%E8%99%AB&Operation=ItemSearch&ResponseGroup=Large&SearchIndex=Books&Service=AWSECommerceService&Timestamp=2009-09-06T02%3A19%3A19.734000Z&Signature=%2B6Jp6e9Ne1o23gy8la6EcJx3f2UrDuZNKldALDaw9DU%3D'
# ElementTreeを生成
root = ElementTree.parse(urllib2.urlopen(request)).getroot()
# XPathを使用してElementTreeを解析[[XPath]]を使用してElementTreeを解析
items = root.findall(q_items)
for item in items:
print '-' * 100
print 'TITLE : {0}'.format(item.find(q_title).text)
print 'AUTHOR AUTHO[[R]] : {0}'.format(item.find(q_author).text)
print 'ASIN : {0}'.format(item.find(q_asin).text)
print 'URL U[[R]]L : {0}'.format(item.find(q_url).text)
print 'IMG : {0}'.format(item.find(q_img).text)
<blockquote>2.5系(GAE/[[Python]])だと、str.formatが使えないため、q_items = './/%s' % qn('Item') とする必要あり。</blockquote>
=====結果=====
----------------------------------------------------------------------------------------------------
TITLE : MW(ムウ) (1) (小学館文庫)
AUTHOR AUTHO[[R]] : 手塚 治虫
ASIN : 4091920047
URL U[[R]]L : http://www.amazon.co.jp/MW-%E3%83%A0%E3%82%A6-%E5%B0%8F%E5%AD%A6%E9%A4%A8%E6%96%87%E5%BA%AB-%E6%89%8B%E5%A1%9A-%E6%B2%BB%E8%99%AB/dp/4091920047%3FSubscriptionId%3D1498TGK1YPN1JATPXXG2%26tag%3Dtypea09-22%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D4091920047 IMG : http://ecx.images-amazon.com/images/I/21AWAK9R3WL21AWAK9[[R]]3WL._SL75_.jpg
----------------------------------------------------------------------------------------------------
TITLE : ブッダ全12巻漫画文庫
AUTHOR AUTHO[[R]] : 手塚 治虫
ASIN : 4267890021
URL U[[R]]L : http://www.amazon.co.jp/%E3%83%96%E3%83%83%E3%83%80%E5%85%A812%E5%B7%BB%E6%BC%AB%E7%94%BB%E6%96%87%E5%BA%AB-%E6%89%8B%E5%A1%9A-%E6%B2%BB%E8%99%AB/dp/4267890021%3FSubscriptionId%3D1498TGK1YPN1JATPXXG2%26tag%3Dtypea09-22%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D4267890021
IMG : http://ecx.images-amazon.com/images/I/51QDB1Q447L._SL75_.jpg
:
===データベースの使用 [sqlite3]===
*http://www.python.jp/doc/nightly/library/sqlite3[[sqlite]]3.html*http://docs.python.jp/2.7/library/sqlite3[[sqlite]]3.html
# -*- encoding: utf-8 -*-
import sqlite3[[sqlite]]3
con = sqlite3[[sqlite]]3.connect('/work/py/test.db')
#create database in RAM[[R]]AM #con = sqlite3[[sqlite]]3.connect(':memory:')
con.execute("create table test (id text, value text, note text)")
(u'3', u'ccc', u'01')
====INSERT例INSE[[R]]T例====
*タブ区切りのテキストファイルの内容をデータベースに投入
*integer primary key に None を渡すと auto number 扱い
conn = sqlite3[[sqlite]]3.connect(r'c:\work\test.db')
c = conn.cursor()
====UPDATE例====
*更新ファイル(キーと更新値を持つ)を読み込んで、UPDATE、なければINSERTする例を読み込んで、UPDATE、なければINSE[[R]]Tする例
*rowcount は SELECT 時には使えない
conn = sqlite3[[sqlite]]3.connect(r'C:\work\test.db')
c = conn.cursor()
... print row
...
(u'2006-01-05', u'BUY', u'RHAT[[R]]HAT', 100, 35.14)
(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
=====名前によるカラムの取得=====
conn = sqlite3[[sqlite]]3.connect(r'C:\work\test.db') conn.row_factory = sqlite3[[sqlite]]3.Row
c = conn.cursor()
c.execute("select * from dict")
for r in c:
# conn.row_factory = sqlite3[[sqlite]]3.Row を行うことで、名前によるカラムの取得が可能になる
# print r[0], r[1], r[2].decode('utf-8'), r[3]
print r["_id"], r["keyword"], r["content"].decode('utf-8'), r['level']

案内メニュー