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

MyMemoWiki

差分

ナビゲーションに移動 検索に移動
編集の要約なし
==Python 標準ライブラリ概観==| [[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.chdir(r'c:\work\py') >>> >>> os.getcwd()
'c:\\work\\py'
====環境変数の参照====
>>> >>> print os.environ['PATH']
/usr/local/pgsql/bin:/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/bin:・・・
====環境変数の設定====
>>> >>> 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.path >>>>>>os.path.exists(r'/test.txt')
True
====ファイルの情報を取得====
>>> >>> import os >>> >>> r = os.stat(r'/test.txt') >>> >>> r
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=4508L, st_atime=1266996480L, st_mtime=1266452528L, st_ctime=1251076742L)
====ファイルのタイムスタンプを取得ファイルの[[タイムスタンプ]]を取得==== >>> >>> import os >>> >>> os.stat('test.txt').st_mtime
1457156166.75
====絶対パスからファイル名のみを取得====
*os.path.basename
>>> >>> import os >>> >>> os.path.basename('c/work/test.txt')
'test.txt'
===ファイルのワイルドカード [glob]===
>>> >>> import glob >>> >>> glob.glob('*.exe')
['python.exe', 'pythonw.exe', 'w9xpopen.exe']
===ファイルの文字コードファイルの[[文字コード]](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]===
print sys.argv
=====結果=====
c:\work\py>>python test.py 1 2 3
['test.py', '1', '2', '3']
===コマンドラインオプション[getopt]===
getopt(args, options[, long_options])
<&lt;blockquote>&gt;options はスクリプトで認識させたいオプション文字と、引数が必要な場 合にはコロン(":")をつけます。<&lt;/blockquote>&gt;
import getopt, 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) を利用する
>>> &gt;&gt;&gt; s = r'AaBbCc' >>> &gt;&gt;&gt; re.sub(r'[a-z]',r'',s)
'ABC'
====一致箇所を抜き出す====
>>> &gt;&gt;&gt; import re >>> &gt;&gt;&gt; re.findall(r'\b[0-9][a-z]+', '1a,2b,cc,dd,4e')
['1a', '2b', '4e']
====グループ名を利用====
=====英文字 + 連番 の連番部分を抜き出す=====
*?P<&lt;名前> &gt; でグループに名前付けを行うことができる
import re
ptn = re.compile(r'[A-Z]+(?P<&lt;SEQ>&gt;[0-9]+)')
for line in lines:
m = ptn.match(line)
*http://www.python.jp/doc/2.5/lib/match-objects.html
<&lt;blockquote>&gt;もしグループが、複数回マッチしたパターンの一部に 含まれていれば、 最後のマッチが返されます。<&lt;/blockquote>&gt;
====正規表現による分割[[正規表現]]による分割====
*re.split を利用
>>> &gt;&gt;&gt; import re >>> &gt;&gt;&gt; re.split('[ \t\n\.\,]', 'this is\ta\npen.')
['this', 'is', 'a', 'pen', '']
|. が改行も含めて、全ての文字とマッチするように指定する
|-
|IGNORECASEIGNO[[R]]ECASE(I)
|大文字小文字を区別しない
|-
|-
|VERBOSE(X)
|冗長な正規表現(もっと、きれいで分かりやすくまとめられる表現)を有効にする。冗長な[[正規表現]](もっと、きれいで分かりやすくまとめられる表現)を有効にする。
|-
|}
===数学 [math]===
*[[Python 数学]] >>> &gt;&gt;&gt; import math >>> &gt;&gt;&gt; pow(2,2)
4
===URL による任意のリソースへのアクセス[urllib]===
====日本語をURLエンコーディングする日本語をURL[[エンコーディング]]する====
=====例 =====
*マップ型オブジェクト、または 2 つの要素をもったタプルからなるシーケンスを、 "URL U[[R]]L にエンコードされた (url-encoded)" に変換して、urlopen() のオプション引数 data に適した形式にする。
import urllib
===インターネットアクセス [urllib2]===
====指定されたURLを読む指定されたU[[R]]Lを読む==== >>> &gt;&gt;&gt; import urllib2 >>> &gt;&gt;&gt; f = urllib2.urlopen('http://typea.info') >>> &gt;&gt;&gt; print f.read(100) <&lt;!DOCTYPE [[HTML ]] PUBLIC "-//W3C//DTD [[HTML ]] 4.01 Transitional//EN">&gt;
print l
====CGIにデータを送信し結果を得る====
>>> &gt;&gt;&gt; import urllib2 >>> &gt;&gt;&gt; req = urllib2.Request[[R]]equest(url='http://typea.info/tips/wiki.cgi',data='action=RSS[[R]]SS') >>> &gt;&gt;&gt; f = urllib2.urlopen(req) >>> &gt;&gt;&gt; print f.read() <&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?>&gt; <&lt;rdf:RDF[[R]]DF
xmlns="http://purl.org/rss/1.0/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xml:lang="ja"
>&gt; <&lt;channel rdf:about="http://typea.info/tips/wiki.cgi?action=LIST">&gt;
:
====CGI のサポート (cgi)====
*http://www.python.jp/doc/release/lib/module-cgi.html
====HTMLタグのエスケープ[[HTML]]タグのエスケープ==== >>> &gt;&gt;&gt; from xml.sax.saxutils import escape >>> &gt;&gt;&gt; escape("<&lt;div>&gt;")
'&lt;div&gt;'
===日付と時刻 [date,datetime,time]===
====基本====
>>> &gt;&gt;&gt; from datetime import date >>> &gt;&gt;&gt; now = date.today() >>> &gt;&gt;&gt; now
datetime.date(2009, 6, 19)
>>> &gt;&gt;&gt; birthday = date(1971, 9, 30) >>> &gt;&gt;&gt; birthday
datetime.date(1971, 9, 30)
>>> &gt;&gt;&gt; age = now - birthday >>> &gt;&gt;&gt; age.days
13777
====[[タイムスタンプ]]====
*[http://ja.wikipedia.org/wiki/ISO_8601 ISO 8601]
>>> &gt;&gt;&gt; from datetime import datetime >>> &gt;&gt;&gt; datetime.now().isoformat()
'2009-07-29T16:44:56.631000'
>>> &gt;&gt;&gt; datetime.utcnow().isoformat()
'2009-07-29T07:45:05.227000'
====タイムスタンプから、datetime [[タイムスタンプ]]から、datetime オブジェクトを作成==== >>> &gt;&gt;&gt; from datetime import datetime >>> &gt;&gt;&gt; ts = os.stat(r'/test.txt').st_ctime >>> &gt;&gt;&gt; datetime.fromtimestamp(ts).isoformat()
'2009-08-24T10:19:02.118895'
====時間の演算 (timedelta)====
|}
>>> &gt;&gt;&gt; from datetime import date >>> &gt;&gt;&gt; from datetime import timedelta >>> &gt;&gt;&gt; today = date.today() >>> &gt;&gt;&gt; today
datetime.date(2010, 1, 25)
>>> &gt;&gt;&gt; new_dt = today - timedelta(days=10) >>> &gt;&gt;&gt; new_dt
datetime.date(2010, 1, 15)
====日付の書式設定====
>>> &gt;&gt;&gt; time.strftime('%Y/%m/%d', time.localtime())
'2010/02/24'
>>> &gt;&gt;&gt; datetime.today().strftime('%Y%m%d')
'20100224'
>>> &gt;&gt;&gt; datetime.fromtimestamp(os.stat(r'/test.txt').st_ctime).strftime('%Y%m%d')
'20090824'
===時間計算 [time]===
====一定時間待つ====
>>> &gt;&gt;&gt; import time >>> &gt;&gt;&gt; time.sleep(2)
===データ圧縮 [zlib]===
>>> &gt;&gt;&gt; import zlib >>> &gt;&gt;&gt; s = 'Common data archiving archi[[vi]]ng and compression formats are directly supported by
modules including: zlib, gzip, bz2, zipfile, and tarfile. '
>>> &gt;&gt;&gt; len(s)
130
>>> &gt;&gt;&gt; t = zlib.compress(s) >>> &gt;&gt;&gt; len(t)
111
>>> &gt;&gt;&gt; zlib.decompress(t) 'Common data archiving archi[[vi]]ng and compression formats are directly supported by modules
including: zlib, gzip, bz2, zipfile, and tarfile. '
>>> &gt;&gt;&gt; zlib.crc32(s)
1515784898
===パフォーマンス計測 [timeit]===
*以下例は、ステートメントが、a * b 初期値 a=2、b=5 の処理時間を計測
>>> &gt;&gt;&gt; from timeit import Timer >>> &gt;&gt;&gt; Timer('a * b', 'a=2;b=5').timeit();
0.12105141854635804
*+1した値を返すinc()関数に、+2した値を返すバグがある例
>>> &gt;&gt;&gt; def inc(val):
... """+1して返す
... >>> &gt;&gt;&gt; print inc(10)
... 11
... """
... return val + 2
...
>>> &gt;&gt;&gt; import doctest >>> &gt;&gt;&gt; doctest.testmod()
*******************************************
File "__main__", line 3, in __main__.inc
(1, 1)
===出力書式===
{{category [[Category:書式}}]]
====reprモジュール [repr]====
*repr モジュールは 巨大で深くネストした内容を簡略表示する、repr() 関数のカスタム版を提供
=====repr() 関数使用=====
>>> &gt;&gt;&gt; import os >>> &gt;&gt;&gt; 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']"
=====repr モジュール使用=====
>>> &gt;&gt;&gt; import os >>> &gt;&gt;&gt; import repr >>> &gt;&gt;&gt; repr.repr(dir(os))
"['F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', ...]"
return l
l = trav('C:\\', 'Python25[[Python]]25')
# 階層構造を持ったリストを出力
====textwrap モジュール [textwrap]====
*textwrap モジュールは、文章の段落を画面幅に合わせるようにフォーマットするモジュールは、[[文章]]の段落を画面幅に合わせるようにフォーマットする
>>> &gt;&gt;&gt; import textwrap >>> &gt;&gt;&gt; txt = """The pprint module offers more sophisticated control over printing
... both built-in and user defined objects in a way that is readable
... by the interpreter. When the result is longer than one line,
... the ``pretty printer'' adds line breaks and indentation to more
... clearly reveal data structure: """
>>>&gt;&gt;&gt; >>> &gt;&gt;&gt; print textwrap.fill(txt, width=20)
The pprint module
offers more
=====localeを使用する=====
>>> &gt;&gt;&gt; import locale >>> &gt;&gt;&gt; locale.setlocale(locale.LC_ALL, 'ja-JP')
'Japanese_Japan.932'
>>> &gt;&gt;&gt; x = 1234567.8 >>> &gt;&gt;&gt; locale.format('%d', x , grouping=True)
'1,234,567'
>>> &gt;&gt;&gt; conv = locale.localeconv() >>> &gt;&gt;&gt; locale.format('%s%.*f', (conv['currency_symbol'], conv['frac_digits'], x), grouping=True)
'\\1,234,568'
=====変換Map(locale.localeconv()) の内容=====
>>> &gt;&gt;&gt; import pprint >>> &gt;&gt;&gt; pprint.pprint(conv)
{'currency_symbol': '\\',
'decimal_point': '.',
*string モジュールは、Template クラスを含んでいる。
*アプリケーションを変更することなしにカスタマイズできる
*プレイスホルダーの書式は、 $ + Pythonの識別子[[Python]]の識別子
*{}で囲むことで、スペースで区切られていなくても良い
*$$で、$をエスケープする
>>> &gt;&gt;&gt; from string import Template >>> &gt;&gt;&gt; t = Template('<&lt;input type="$element_name" value="hello${element_value}world!" />&gt;') >>> &gt;&gt;&gt; t.substitute(element_name='text', element_value=' python ') '<&lt;input type="text" value="hello python world!" />&gt;'
====substitute メソッド と safe_substituteメソッド====
*substitute メソッドはプレースホルダーと置き換える値がが提供されない場合KeyErrorを引き起こす
*safe_substituteメソッドは、その場合、プレースホルダーをそのままにする。
>>> &gt;&gt;&gt; from string import Template >>> &gt;&gt;&gt; t = Template('$field_a, $field_b') >>> &gt;&gt;&gt; d = dict(field_a='FIELD_AF[[IE]]LD_A') >>> &gt;&gt;&gt; t.substitute(d)
Traceback (most recent call last):
File "<&lt;stdin>&gt;", line 1, in <&lt;module>&gt; 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'
>>> &gt;&gt;&gt; t.safe_substitute(d) 'FIELD_AF[[IE]]LD_A, $field_b'
====デリミタのカスタマイズ====
*Templete のサブクラスでは、カスタムデリミタを使用できる。
>>> &gt;&gt;&gt; from string import Template >>> &gt;&gt;&gt; class PctDlimTemplate(Template):
... delimiter = '%'
...
>>> &gt;&gt;&gt; t = PctDlimTemplate('<&lt;input type="%element_name" value="hello%{element_value}world!" />&gt;') >>> &gt;&gt;&gt; t.substitute(element_name='text', element_value=' python ') '<&lt;input type="text" value="hello python world!" />&gt;'
===シリアライズ [pickle]===
====シリアライズする====
Pythonオブジェクトをシリアライズする簡単な例[[Python]]オブジェクトをシリアライズする簡単な例 >>> &gt;&gt;&gt; d = { 'k1':123, 'k2':456, 'k3':789} >>> &gt;&gt;&gt; d
{'k3': 789, 'k2': 456, 'k1': 123}
>>> &gt;&gt;&gt; import pickle >>> &gt;&gt;&gt; f = open(r'c:\work\py\dat.txt', 'w') >>> &gt;&gt;&gt; pickle.dump(d, f) >>> &gt;&gt;&gt; f.close();
====デシリアライズする====
>>> &gt;&gt;&gt; f = open(r'c:\work\py\dat.txt') >>> &gt;&gt;&gt; e = pickle.load(f) >>> &gt;&gt;&gt; e
{'k3': 789, 'k2': 456, 'k1': 123}
*struct モジュールは pack() 、unpack() 関数を可変長のバイナリレコードフォーマットの作業用に提供する
>>> &gt;&gt;&gt; import struct >>> &gt;&gt;&gt; struct.pack('hhl',1,2,3)
'\x01\x00\x02\x00\x03\x00\x00\x00'
>>> &gt;&gt;&gt; struct.unpack('hhl','\x01\x00\x02\x00\x03\x00\x00\x00')
(1, 2, 3)
>>> &gt;&gt;&gt; struct.calcsize('hhl')
8
!書式
!C言語の型
!Pythonの型[[Python]]の型
|-
|x
*これは[http://typea-mixi01.appspot.com/yh_s?q=%E6%B5%85%E3%81%84%E3%82%B3%E3%83%94%E3%83%BC 浅いコピー]なので、トップレベルのオブジェクトしかコピーされない。
=====コピー例=====
>>> &gt;&gt;&gt; l1 = [1] # 元オブジェクト >>> &gt;&gt;&gt; l2 = [l1] # 元オブジェクトをそのままセット >>> &gt;&gt;&gt; l3 = [l1[:]] # 元オブジェクトをコピーしてセット >>> &gt;&gt;&gt; m1 = {1:l1, 2:l2, 3:l3} >>> &gt;&gt;&gt; m1
{1: [1], 2: [[1]], 3: [[1]]}
>>> &gt;&gt;&gt; l1[0] = 9 # 元オブジェクトを 1 -> &gt; 9 に変更 >>> &gt;&gt;&gt; m1
{1: [9], 2: [[9]], 3: [[1]]} # コピーしたものは影響を受けない
=====ネストしたオブジェクトはコピーされていない=====
>>> &gt;&gt;&gt; m1
{1: [9], 2: [[9]], 3: [[1]]}
>>> &gt;&gt;&gt; m2 = {4:m1.copy()} # コピーした内容をディクショナリに格納 >>> &gt;&gt;&gt; l1[0] = 10 # 大元の値を 9 -> &gt; 10 変更すると >>> &gt;&gt;&gt; m2
{4: {1: [10], 2: [[10]], 3: [[1]]}} # 反映されてしまう
====[http://typea-mixi01.appspot.com/yh_s?q=%E6%B7%B1%E3%81%84%E3%82%B3%E3%83%94%E3%83%BC 深いコピー]====
*深いコピーを行うには、copyモジュールの、deepcopy関数を使用する。
>>> &gt;&gt;&gt; import copy >>> &gt;&gt;&gt; m1
{1: [10], 2: [[10]], 3: [[1]]}
>>> &gt;&gt;&gt; m3 = {5:copy.deepcopy(m1)} >>> &gt;&gt;&gt; m3
{5: {1: [10], 2: [[10]], 3: [[1]]}}
>>> &gt;&gt;&gt; l1[0] = 99 # 大元オブジェクトを 10->&gt;99 に変更しても >>> &gt;&gt;&gt; m3
{5: {1: [10], 2: [[10]], 3: [[1]]}} # コピーした時点の値が保持されている
====リストのコピー====
>>> &gt;&gt;&gt; l = range(10) >>> &gt;&gt;&gt; k = l[:] >>> &gt;&gt;&gt; k
===マルチスレッド [threading]===
====非同期にカウントアップ====
print 'Thread 2 work done'
=====実行結果例=====
>&gt;python test.py
#Thread 1 0
#Thread 1 1
logging.error("logging")
=====実行結果=====
>&gt;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():
=====実行結果=====
>&gt;python myapp.py
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)
<&lt;blockquote>&gt;2.5系(GAE/[[Python]])だと、str.formatが使えないため、q_items = './/%s' % qn('Item') とする必要あり。<&lt;/blockquote>&gt;
=====結果=====
----------------------------------------------------------------------------------------------------
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()
ptn = re.compile(r'^(?P<&lt;LVL>&gt;[0-9])[ ](?P<&lt;WD>&gt;.+)')
fd = open(r'C:\work\update.txt', 'r')
for l in fd:
c.execute("update dict set level=? where keyword=?", (lvl, kw))
if c.rowcount > &gt; 0:
pass
else:
''iteratorの例''
>>> &gt;&gt;&gt; c = conn.cursor() >>> &gt;&gt;&gt; c.execute('select * from stocks order by price') >>> &gt;&gt;&gt; for row in c:
... 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']
r = cur.execute("select count(key) from harai")
print r.fetchone()[0]
===JSONエンコードとデコード [json]===
*https://docs.python.org/ja/3/library/json.html
 
====書式と文字化けの対処====
<pre>
print(json.dumps(song, indent=2, ensure_ascii=False))
</pre>
====ファイルからロード====
<pre>
with open(file, 'r') as inf:
o = json.load(inf)
print(o)
</pre>
 
==UUIDを使用する==
*http://99blues.dyndns.org/blog/2010/07/uuid_generate/
>>> &gt;&gt;&gt; import uuid >>> &gt;&gt;&gt; uuid.uuid4()
UUID('68c6d889-a64e-4e94-86f0-14012fc90364')
==メールを送信する==
**[http://typea.info/blg/glob/2015/06/centospython.html CentOSにメールサーバーを構築してPythonからメールを送信する]

案内メニュー