LoginSignup
1
3

More than 5 years have passed since last update.

型+文字列+DB接続 | 第2回pythonリモート社内勉強会

Last updated at Posted at 2017-12-10

「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

組み込み型

  1. 真理値判定(TRUE、FALSE)
  2. ブール演算(and, or, not)
  3. 比較(<, <=, >, >=, ==, !=, is, is not)
  4. 数値型(int, float, complex)

https://ja.wikipedia.org/wiki/%E8%A4%87%E7%B4%A0%E6%95%B0

  1. シーケンス型(list, tuple, range)

例:
list ・・・ [1,2,3]
tuple ・・・ (1,2,3)
range ・・・ range(1,10)

  1. テキストシーケンス型(str)
  2. バイナリシーケンス型(bytes, bytearray, memoryview)
  3. set(集合)型(set, frozenset)
  4. マッピング型(dict)

データ型

  1. datetime — 基本的な日付型および時間型
  2. calendar — 一般的なカレンダーに関する関数群
  3. collections — コンテナデータ型
  4. collections.abc — コレクションの抽象基底クラス
  5. heapq — ヒープキューアルゴリズム
  6. bisect — 配列二分法アルゴリズム
  7. array — 効率のよい数値アレイ
  8. weakref — 弱参照
  9. types — 動的な型生成と組み込み型に対する名前
  10. copy — 浅いコピーおよび深いコピー操作
  11. pprint — データ出力の整然化
  12. reprlib — もう一つの repr() の実装
  13. enum — 列挙型のサポート

文字列処理

https://qiita.com/tomotaka_ito/items/594ee1396cf982ba9887
http://docs.python.jp/3.6/library/string.html

%s - 文字列として展開
%d - 整数として展開
%f - 小数点数として展開

string.py

#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をインストール
スクリーンショット 2017-12-08 3.04.50.png

m_area.sql

# サンプルテーブル
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

database.py

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

math.py
numpy.py

ファイル・ディレクトリ制御

file.py

関数型プログラミング

functional.py

並列実行

parallel.py

デバッグ・プロファイラ

debug.py

メール・JSON・API

api.py

後半(応用編)の予定

  1. DBを用いたクエリビルダ
  2. WEBアプリケーション
  3. API実装
  4. csvファイル制御
  5. tensorflow
  6. レコメンドエンジンの実装(スコアリング)
  7. 自然言語処理プログラムの実装(※mecab等も活用?)
  8. 画像処理エンジンの実装(※deep learningを実装?)
  9. 回帰分析などの統計プログラムの実装
  10. その他アルゴリズムの構築、ハッカソン形式
1
3
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
1
3