LoginSignup
17
26

More than 5 years have passed since last update.

pythonの標準ライブラリどんなものあるかみてみた

Last updated at Posted at 2018-12-09

はじめに

pythonの基礎として、標準ライブラリについて記載していきます。

osモジュール

osモジュールを利用することでOSと対話をすることができます。

>>>import os
>>> os.getcwd()
'/Users/hoge/Desktop/'
>>> os.system("mkdir test_dir")
0
>>> os.chdir("/Users/hoge/Desktop/test_dir")
>>> os.getcwd()
'/Users/hiropy/Desktop/test_dir'

この時from os import *ではなく、import osを使うことで組み込み関数 open()が os.opon()が混同されることを避けることができます。

組み込み関数 dir()および help() は、 os のような大規模なモジュールで作業をするときに、対話的な操作上の助けになります:

>>> import os
>>> dir(os)
['CLD_CONTINUED', 'CLD_DUMPED', 'CLD_EXITED', 'CLD_TRAPPED', 'DirEntry', 'EX_CANTCREAT', ...
>>> help(os)
#新しい画面でhelpの内容が表示されます。

shutilモジュール

ファイルやディレクトリの管理作業にはshutilモジュールを使います。

>>> import shutil
>>> os.getcwd()
'/Users/hoge/Desktop'
>>> os.chdir("/Users/hoge/Desktop/test_dir")
>>> os.system("echo abc > 'test.txt'")
0
>>> shutil.copyfile('test.txt', 'test2.txt')
'test2.txt'
>>> shutil.move("test2.txt",'/Users/hoge/Desktop')
'/Users/hoge/Desktop/test2.txt'

上記のように、ファイルのコピーと移動をすることができました。

globモジュール

globモジュールを使うことで、ディレクトリのワイルドカード検索からファイルのリストを生成することができます。

>>> import glob
>>> glob.glob("*.txt")
['test.txt', 'test2.txt']

sysモジュール

コマンドライン引数

コマンドライン引数は sys モジュールの argv 属性にリストとして保存されています。

sample.py
>>> import sys
>>>argvs = sys.argv
>>> print(argvs)

以下のように出力することができます。

$ python sample.py a b c
['sample.py', 'a', 'b', 'c']

getopt モジュール

getopt モジュールは、 sys.argvを Unixのgetopt() 関数に従って処理を行います。

エラー出力のリダイレクトとプログラムの終了

sysモジュールは、標準入力や標準出力、終了などのシグナルを扱うためのモジュールです。

>>> sys.stdout.write("出力\n")
出力
3
>>> sys.stderr.write('Warning\n')
Warning

以下では、入力されたものをを受け取って変数に渡します。

read():ctrl+dが押されるまで、入力を受け取る

>>> hoge = sys.stdin.read()
a 
b
c
d
e
>>> 
>>> hoge
'a\nb\nc\nd\ne\n'

readline():Enterが押されるまで、入力を受け取る

>>> hogeho = sys.stdin.readline()
abcde 

readlines():ctrl+dが押されるまで、入力を受け取る
※read() との違いは、リストに格納することであり、Enter ごとにリストの要素が追加される
Enter で入力された改行はそのまま残る

>>> hogege = sys.stdin.readlines()
a
b
c
d
e
>>> hogege
['a\n', 'b\n', 'c\n', 'd\n', 'e\n']

sys.exit() でスクリプトを終了させることができます。

reモジュール

文字列のパターンマッチングとしてre モジュールで、より高度な文字列処理のための正規表現を提供しています。正規表現は複雑な一致検索や操作に対して簡潔で最適化された解決策を提供します:

>>> import re
>>> re.find(r'\bh[a-z]*', 'I am happy')
['happy']
>>> raw_text = "abcdefgh01234567"
>>> sub_text = re.sub(r'[a-z]', "x", raw_text)
>>> print(sub_text)
xxxxxxxx01234567

数学

math モジュールは、浮動小数点演算のための C 言語ライブラリ関数にアクセスする手段を提供しています:

>>> import math
>>> math.pi
3.141592653589793
>>> math.cos(math.pi)
-1
>>> math.cos(math.pi/2)
6.123233995736766e-17
>>> math.log(1024, 2)
10.0

randomモジュールでランダムサンプリングなどもできます。

>>> import random
>>> random.choice(['A','B','C'])
'B'
>>> random.sample(range(100), 10)
[69, 80, 16, 10, 84, 83, 70, 77, 4, 55]

乱数発生

>>> random.random()
0.023667039896831055

statisticsモジュールで記述統計の計算も可能です。

>>> import statistics
>>> import random
>>> data = random.sample(range(100), 10)
[61, 16, 90, 25, 31, 1, 56, 10, 86, 30]
>>> statistics.mean(data)
54.4
>>> statistics.median(data)
56.5
>>> statistics.variance(data)
850.9333333333333

日付と時刻

datetimeモジュールでは日付や時刻を操作することができます。いろんな表記の仕方できます。

>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2018, 12, 7)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-07-18. 07 Dec 2018 is a Friday on the 07 day of December.'

生まれてからの日数も簡単に計算できます。

>>> birthday = date(1985,12,14)
>>> age = now - birthday
>>> age.days
12046

データ圧縮

一般的なデータアーカイブと圧縮形式は、後述のモジュールによって直接利用することが可能です。 zlib, gzip, bz2, lzma, zipfile, tarfile。

>>> import zlib
>>> s = b'where what who when why how'
>>> len(s)
27
>>> t = zlib.compress(s)
>>> t
b"x\x9c+\xcfH-JU(\xcfH,\x01\x12\xf9@\x9c\x9a\x07$*\x152\xf2\xcb\x01\x8e'\n\x16"
>>> len(t)
30
>>> zlib.decompress(t)
b'where what who when why how'
>>> zlib.crc32(s)
3743703071

パフォーマンスの計測

timeitモジュールを使えばを利用することでパフォーマンスを計測します。
リファクタリングなどをした際に、検証で使うことがあります。マジックコマンドで利用することが多いです。

以下はアルゴリズムの入門で出てくる2つの変数の値の交換

>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.053042817999084946
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.044962756997847464

timeitのほかにも、profileやpstatsモジュールも存在します。

出力のフォーマット

pprintモジュール

list型やdict型などのオブジェクトを整形して出力・表示したりすることができます。わかりやすくprint()と合わせてかくにんしてみます。

>>> import pprint
>>> dic = [{'Name': 'hiro', 'age': 33}, 
...      {'Name': 'yuki', 'age': 35},
...      {'Name': 'hiroyuki', 'age': 40}]
>>>
>>> print(l)
[{'Name': 'hiro', 'age': 33}, {'Name': 'yuki', 'age': 35}, {'Name': 'hiroyuki', 'age': 40}]
>>>
>>> pprint.pprint(l)
[{'Name': 'hiro', 'age': 33},
 {'Name': 'yuki', 'age': 35},
 {'Name': 'hiroyuki', 'age': 40}]

引数に1行の文字数をしているすることも可能です。デフォルトでは80
になっています。辞書のkeyとvalueで改行されたり、数値の途中で改行されたりはせず、また文字列の途中で改行されることもありません。

>>> pprint.pprint(l,width=20)
[{'Name': 'hiro',
  'age': 33},
 {'Name': 'yuki',
  'age': 35},
 {'Name': 'hiroyuki',
  'age': 40}]

このほかにも、ネストの深さのdepthや、インデントの幅指定indent、改行を最小限にするcompact、フォーマットを変えるpformatなどの機能も存在します。

textwrapモジュール

段落で構成された文章を、指定した幅に収まるように調整することができます。
なんとなくトランプ大統領の就任演説の英文を拝借。

>>> import textwrap
>>> doc = """
... Chief Justice Roberts, President Carter, President Clinton, President Bush, President Obama, fellow Americans, and people of the world:
... thank you.
... We, the citizens of America, are now joined in a great national effort to rebuild our country and to restore its promise for all of our people.
... Together, we will determine the course of America and the world for years to come."""
>>> 
>>> print(textwrap.fill(doc, width=40))
 Chief Justice Roberts, President
Carter, President Clinton, President
Bush, President Obama, fellow Americans,
and people of the world: thank you. We,
the citizens of America, are now joined
in a great national effort to rebuild
our country and to restore its promise
for all of our people. Together, we will
determine the course of America and the
world for years to come.

>>> print(textwrap.fill(doc, width=60))
 Chief Justice Roberts, President Carter, President Clinton,
President Bush, President Obama, fellow Americans, and
people of the world: thank you. We, the citizens of America,
are now joined in a great national effort to rebuild our
country and to restore its promise for all of our people.
Together, we will determine the course of America and the
world for years to come.
>>> 

localeモジュール

データ表現形式のデータベースにアクセスし、ロケール設定を制御することができます。わかりやすくdatetimeを利用します。

>>> import datetime
>>> import locale
>>> 
>>> dt = datetime.datetime(2018, 12, 8)
>>> print(dt)
2018-12-08 00:00:00
>>> print(dt.strftime('%A, %a, %B, %b'))
Sutuday, Sut, December, Dec
>>> print(locale.getlocale(locale.LC_TIME))
(None, None)
>>> locale.setlocale(locale.LC_TIME, 'ja_JP.UTF-8')
>>> print(locale.getlocale(locale.LC_TIME))
('ja_JP', 'UTF-8')
>>> print(dt.strftime('%A, %a, %B, %b'))
土曜日, , 12, 12

文字列テンプレート

stringモジュール

アプリケーションを修正することなしにアプリケーションの出力をカスタマイズすることができます。
「\$」と英数字とアンダースコアからなる識別子をplaceholderに使います。
placeholderを{}で囲うことで、後ろにスペースを挟まずに文字を続けることができ、$$のようにすると、$をエスケープすることができます。ドルをエスケープする機会があまり無いですが、例を以下に。

>>> from string import Template
>>> test = Template('${station}駅で、$$10を配る${human}がいるらしい。')
>>> t.substitute(station='有楽町', human='小人')
'有楽町駅で、$10を配る小人がいるらしい。'

substitute()メソッドは、相当する値が辞書やkwd引数にない場合にKeyErrorを返します。この場合はsafe_substitute()を使うことで、エラーを明示することができます。

>>> from string import Template
>>> test = Template('${station}駅で、$$10を配る${human}がいるらしい。')
>>> t.safe_substitute(station='有楽町', how_much='$100')
'有楽町駅で、$10を配る${human}がいるらしい。'

終わり

この他にもライブラリはありますが、長くなったのでここら辺で終わりにします。

17
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
26