「python社内勉強会&ハッカソン」の公開ログになります。
今回は、「型」、「文字列処理」、「データベース接続」について。
この勉強会について
各回30〜60分程度。ダラダラとはやらずpythonのwhy、whatを共有していく時間になります。
基本的なプログラミングなどの実装は会内はやらず、実行デモ程度を予定しています。宿題も特にありませんので各自勉強したことを再学習していってください。
前半(基礎編)
これまでの勉強会の過去ログはこちら。
第1回 : https://qiita.com/classfox/items/edba3e8971aaa067b88b
第2回 : https://qiita.com/classfox/items/095c4f4b8aa9247a4392
第3回 : https://qiita.com/classfox/items/825116980ac7ca255a13
第4回 : https://qiita.com/classfox/items/9a4b8a513fd5b642534d
組み込み型
- 真理値判定(TRUE、FALSE)
- ブール演算(and, or, not)
- 比較(<, <=, >, >=, ==, !=, is, is not)
- 数値型(int, float, complex)
※https://ja.wikipedia.org/wiki/%E8%A4%87%E7%B4%A0%E6%95%B0
- シーケンス型(list, tuple, range)
例:
list ・・・ [1,2,3]
tuple ・・・ (1,2,3)
range ・・・ range(1,10)
- テキストシーケンス型(str)
- バイナリシーケンス型(bytes, bytearray, memoryview)
- set(集合)型(set, frozenset)
- マッピング型(dict)
データ型
- datetime — 基本的な日付型および時間型
- calendar — 一般的なカレンダーに関する関数群
- collections — コンテナデータ型
- collections.abc — コレクションの抽象基底クラス
- heapq — ヒープキューアルゴリズム
- bisect — 配列二分法アルゴリズム
- array — 効率のよい数値アレイ
- weakref — 弱参照
- types — 動的な型生成と組み込み型に対する名前
- copy — 浅いコピーおよび深いコピー操作
- pprint — データ出力の整然化
- reprlib — もう一つの repr() の実装
- enum — 列挙型のサポート
文字列処理
https://qiita.com/tomotaka_ito/items/594ee1396cf982ba9887
http://docs.python.jp/3.6/library/string.html
%s - 文字列として展開
%d - 整数として展開
%f - 小数点数として展開
# coding: UTF-8
import re
# 連結
a = 'Python'
b = '3.6.3'
c = a + b
print(c)
print(a + b)
print()
# 配列を,で連結して表示する
strings = ['classfox', 'python', 'study']
print(','.join(strings))
print()
# 繰り返し
s = 'classfox! '
print(s * 3)
print()
# 値の埋め込み
a = 'Python'
b = 'a programming language'
print('%s is %s' % (a, b))
print()
# discオブジェクト内のキーを指定
v = dict(first='Michael', family='Jackson')
print('He is %(first)s, %(first)s %(family)s.' % v)
print()
# 置換
s = 'Today is Monday.'
print(s.replace('Monday', 'Sunday'))
print()
# 正規表現(http://docs.python.jp/3.6/library/re.html)
s = 'Hello World'
print(re.sub(r"[a-z]", "A", s))
print()
# N文字目の文字を取得
s = 'abc'
print(s[1])
print()
s = "This is a classfox."
print(s[0:4])
print()
# 文字列内検索
s = 'abcabcabc'
index = s.find('b', 2)
print('start=%d' % index)
print()
# 全ターゲットを検索
target = 'b'
index = -1
while True:
index = s.find(target, index + 1)
if index == -1:
break
print('start=%d' % index)
print()
# 1文字ずつ処理
s = 'classfox'
for i in range(len(s)):
c = s[i]
print(c,end='')
print()
# intを文字列に変換する
v = 1
print(str(v))
print('%d' % v)
print()
# floatを文字列に変換する
f = 1.234
print(str(f))
print('%f' % f)
print()
# listを文字列に変換する, tupleを文字列に変換する
v = [1,2,3]
print(str(v))
print('%s' % v)
print()
# joinを使って組み立てる例
print('<' + ('/'.join([ str(item) for item in v ])) + '>')
print()
# dictを文字列に変換する
v = dict(a=1, b=2)
print(str(v))
print('%s' % v)
DB接続
今回は、デモではmysqlのみを確認。他のDBは上記サイトにて情報が掲載されています。
mysql-connector-pythonをインストール
# サンプルテーブル
CREATE TABLE `m_area` (
`area_id` int(11) NOT NULL AUTO_INCREMENT,
`area_category_id` int(11) NOT NULL,
`prefecture_id` int(11) NOT NULL,
`area_name` varchar(256) NOT NULL,
`del_flg` tinyint(4) NOT NULL DEFAULT '0',
`create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_date` datetime NOT NULL,
PRIMARY KEY (`area_id`)
) ENGINE=InnoDB AUTO_INCREMENT=71 DEFAULT CHARSET=utf8
import mysql.connector
try:
#mysqlデータベースへの接続
cnn = mysql.connector.connect(host='localhost',
port=3306,
db='testdb',
user='root',
passwd='hogehoge',
charset="utf8")
cur = cnn.cursor()
#クエリ実行(select文)
print("==== select文 ====")
area_category_id = 2
prefecture_id = 27
cur.execute("""select area_id, area_name from m_area where area_category_id = %s and prefecture_id = %s""", (area_category_id, prefecture_id))
rows = cur.fetchall()
for row in rows:
print("%d %s" % (row[0], row[1]))
#クエリ実行(insert文)
print("==== insert文 ====")
area_category_id = 8
prefecture_id = 99
area_name = "テスト県"
cur.execute("""insert into m_area (area_category_id, prefecture_id, area_name, del_flg, create_date, update_date) values (%s, %s, %s, '0', '2017-12-08 00:00:00', '2017-12-08 00:00:00')""", (area_category_id, prefecture_id, area_name))
cnn.commit()
# クエリ実行(select文)
print("==== insertされたか確認 ====")
cur.execute("""select area_id, area_name from m_area where area_category_id = %s and prefecture_id = %s""",
(area_category_id, prefecture_id))
rows = cur.fetchall()
for row in rows:
print("%d %s" % (row[0], row[1]))
except (mysql.connector.errors.ProgrammingError) as e:
print(e)
第2回はここまで。次回以降のラインナップは以下を参照ください。
※内容が変更となる場合もあります。
これまでの勉強会の過去ログはこちら。
第1回 : https://qiita.com/classfox/items/edba3e8971aaa067b88b
第2回 : https://qiita.com/classfox/items/095c4f4b8aa9247a4392
第3回 : https://qiita.com/classfox/items/825116980ac7ca255a13
第4回 : https://qiita.com/classfox/items/9a4b8a513fd5b642534d
数学関数、Numpy
https://docs.python.jp/3/library/numeric.html
https://docs.python.jp/3/library/math.html
ファイル・ディレクトリ制御
関数型プログラミング
並列実行
デバッグ・プロファイラ
メール・JSON・API
後半(応用編)の予定
- DBを用いたクエリビルダ
- WEBアプリケーション
- API実装
- csvファイル制御
- tensorflow
- レコメンドエンジンの実装(スコアリング)
- 自然言語処理プログラムの実装(※mecab等も活用?)
- 画像処理エンジンの実装(※deep learningを実装?)
- 回帰分析などの統計プログラムの実装
- その他アルゴリズムの構築、ハッカソン形式