Contenu connexe Similaire à 「Python言語」はじめの一歩 / First step of Python (20) Plus de Takanori Suzuki (20) 「Python言語」はじめの一歩 / First step of Python22. Python 2 と 3
• 最新は Python 2.7.10 と 3.4.3(もうすぐ3.5.0)
• 一部後方互換性なし
• 今日は Python 3 ベースでやります
25. インデントでブロック構造
for i in range(10):
if i % 5 == 0:
print('ham')
elif i % 3 == 0:
print('eggs')
else:
print('spam')
26. 対話モード
$ python
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more
information.
>>> for i in range(10):
... if i % 5 == 0:
... print('ham')
... elif i % 3 == 0:
... print('eggs')
... else:
... print('spam')
...
ham
spam
spam
:
eggs
35. 関数と組み込み関数
>>> def add(a, b):
... return a + b
...
>>> add(1, 3)
4
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
39. if, elif, else: 条件分岐
def fizzbuzz(num):
if num % 3 == 0 and num % 5 == 0:
return 'FizzBuzz'
elif num % 3 == 0:
return 'Fizz'
elif num % 5 == 0:
return 'Buzz'
else:
return str(num)
43. データ型
>>> type(1)
<class 'int'>
>>> type(1.1)
<class 'float'>
>>> type('日本語')
<class 'str'>
>>> '日本語'.encode('utf-8')
b'xe6x97xa5xe6x9cxacxe8xaax9e'
>>> type('日本語'.encode('utf-8'))
<class 'bytes'>
44. 文字列の操作
>>> 'Hello World' # シングルクォーテーション
'Hello World'
>>> "Hello World" # ダブルクォーテーション
'Hello World'
>>> 'Mt.' + 'Fuji' # 文字列の連結
'Mt.Fuji'
>>> 'python'[2:5] # スライス
'tho'
>>> 't' in 'python' # 文字列の存在チェック
True
>>> 'pain-au-chocolat'.split('-') # 文字列分割
['pain', 'au', 'chocolat']
46. list: リスト
>>> animals = ['cat', 'dog', 'snake']
>>> type(animals)
<class 'list'>
>>> animals[0] # 要素を取得
'cat'
>>> animals[1:] # スライスも使える
['dog', 'snake']
>>> animals.append('elephant') # 要素を追加
>>> for animal in animals: # ループで取り出す
... print(animal)
...
cat
dog
snake
elephant
47. tuple: タプル
>>> animals = ('cat', 'dog', 'snake')
>>> type(animals)
<class 'tuple'>
>>> animals[0] # 要素を取得
'cat'
>>> animals[1:] # スライスも使える
('dog', 'snake')
>>> animals.append('elephant') # 追加はエラー
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute
'append'
>>> 'spam', # 要素が一つのtupleを作成
('spam',)
48. dict: 辞書
>>> user_info = {
... 'firstname': 'takanori',
... 'lastname': 'suzuki',
... }
>>> user_info
{'firstname': 'takanori', 'lastname': 'suzuki'}
>>> user_info['firstname'] # 要素を取得
'takanori'
>>> 'firstname' in user_info # キーの存在チェック
True
>>> for key, value in user_info.items():
... print(key, value)
...
firstname takanori
lastname suzuki
49. set: 集合
>>> {'spam', 'ham'}
{'ham', 'spam'}
>>> {'spam', 'spam', 'spam'}
{'spam'}
>>> set1 = {'spam', 'ham'}
>>> set2 = {'ham', 'eggs'}
>>> set1 & set2 # 集合の積
{'ham'}
>>> set1 | set2 # 集合の和
{'ham', 'eggs', 'spam'}
50. ファイル操作
>>> with open('todo.txt') as f: # ファイルを開く
... todo_str = f.read()
...
>>> with open('memo.txt', 'w') as f: # 書き込む
... f.write('Hello worldn')
...
12
>>> with open('memo.txt', 'a', encoding='utf-8')
as f: # 文字コード指定して追記
... f.write('こんにちは世界n')
...
8
51. モジュール
def add(a, b):
return a + b
def sub(a, b):
return a - b
>>> import calc
>>> calc.add(1, 3)
4
>>> from calc import sub
>>> sub(5, 2)
3
calc.py
54. printが文から関数に
>>> print # 空行を出力
>>> print 'Hello Python 2!'
Hello Python 2!
Python 2のprint文
Python 3のprint関数
>>> print() # 空行を出力
>>> print('Hello Python 3!')
Hello Python 3!
61. re: 正規表現
>>> import re
>>> m = re.search('py(thon)', 'python')
>>> m
<_sre.SRE_Match object; span=(0, 6),
match='python'>
>>> m.group()
'python'
>>> m.group(0)
'python'
>>> m.group(1)
'thon'
62. sys, os: システムパラメータとOS
>>> import os
>>> os.mkdir('spam')
>>> os.chdir('spam')
>>> os.getcwd() # 現在のディレクトリ
'/Users/takanori/hikalab/spam'
>>> import sys
>>> sys.exit(1)
63. datetime: 日付と時刻
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.isoformat()
'2015-08-17T18:17:49.623626'
>>> today = datetime.date(2015, 8, 18)
>>> nextyear = datetime.date(2016, 1, 1)
>>> delta = nextyear - today
>>> delta.days
136
64. math, random: 数学関数と乱数
>>> import math
>>> math.pi
3.141592653589793
>>> math.sqrt(2)
1.4142135623730951
>>> import random
>>> random.randint(1, 1000)
632
>>> data = ['spam', 'ham', 'eggs']
>>> random.choice(data)
'eggs'
>>> random.shuffle(data)
>>> data
['spam', 'eggs', 'ham']
65. itertools: イテレータ生成関数
>>> import itertools
>>> list(itertools.chain('ABC', 'DEF'))
['A', 'B', 'C', 'D', 'E', 'F']
>>> list(itertools.combinations('ABCD', 2))
[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B',
'C'), ('B', 'D'), ('C', 'D')]
67. json: JSONエンコーダ、デコーダ
>>> import json
>>> data = {'spam': 'SPAM',
... 'ham': True,
... 'eggs': None,
... }
>>> json_str = json.dumps(data)
>>> json_str
'{"eggs": null, "ham": true, "spam": "SPAM"}'
>>> json.loads(json_str)
{'ham': True, 'eggs': None, 'spam': 'SPAM'}
72. pip のインストール
$ wget https://bootstrap.pypa.io/get-pip.py
$ python get-pip.py
$ pip install (package name)
73. virtualenv のインストール
$ pip install virtualenv
$ virtualenv venv
$ . venv/bin/activate
(venv)$ pip install requests
(venv)$ python
>>> import requests
>>> quit()
(venv)$ deactivate
$ python
>>> import requests
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'requests'
74. dateutil: 日時操作の強力な拡張
$ pip install python-dateutil
>>> from dateutil.parser import parse
>>> parse("Mon Jan 26 20:34:20 UTC 2015")
datetime.datetime(2015, 1, 26, 20, 34, 20,
tzinfo=tzutc())
>>> parse("2015-01-26 20:34:20 JST")
datetime.datetime(2015, 1, 26, 20, 34, 20,
tzinfo=tzlocal())
>>> parse("Jan-26-2015")
datetime.datetime(2015, 1, 26, 0, 0)
75. Requests: HTTPクライアント
$ pip install requests
>>> import requests
>>> url = 'http://connpass.com/api/v1/event/?keyword=python'
>>> r = requests.get(url) # URLにアクセス
>>> print(r.status_code) # ステータスコードを取得
200
>>> for event in r.json()['events'][:3]: # 先頭3件を取得
... print(event['title']) # イベントのタイトルを取得
...
Python mini hack-a-thon 夏山合宿 2015
SoftLayer Bluemix Summit 2015
コミュニティ運営の秘訣を知りたい人、『Sync Meetup』に集まれ!!
76. BeautifulSoup4: HTML, XMLパーサ
$ pip install beautifulsoup4
>>> from bs4 import BeautifulSoup
>>> import requests
>>> r = requests.get('http://docs.python.jp/3/library/')
>>> soup = BeautifulSoup(r.content, "html.parser") # HTMLパース
>>> toctree = soup.find('div', 'toctree-wrapper') # 目次を取得
>>> links = toctree.find_all('a') # aタグを全て取得
>>> len(links) # リンクの数を取得
358
>>> for link in links[:3]: # 先頭3件を取得
... print(link.text)
...
1. はじめに
2. 組み込み関数
3. 組み込み定数
77. Pillow: 画像処理ライブラリ
$ pip install pillow
>>> from PIL import Image
>>> image = Image.open('sample.jpg') # 画像を読み込み
>>> half = (image.size[0] / 2, image.size[1] / 2)
>>> half = image.resize(half, Image.ANTIALIAS) # 縮小
>>> half.save('sample-half.jpg') # 画像を保存
>>> rotate = image.transpose(Image.ROTATE_90) # 回転
>>> rotate.save('sample-rotate.png') # PNGで保存
78. コーディング規約
• PEP 0008 -- Style Guide for Python Code
• https://www.python.org/dev/peps/pep-0008/
• pep8: コーディング規約のチェック
• autopep8: 自動的にPEP8形式にする
• flake8: pep8 + ソースコードのチェック
84. PyCon JP 2015
• https://pycon.jp/2015/ja/
• 10月9日(金): チュートリアル
• 10月10日(土)、11日(日): カンファレンス
• 10月12日(月・祝): 開発スプリント