2016年8月21日日曜日

開発環境

入門 Python 3 (Bill Lubanovic (著)、 斎藤 康毅(監修)、 長尾 高弘 (翻訳)、オライリージャパン)の8章(データの行き先)、8.7(復習問題)を取り組んでみる。

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-


print('8-1')
test1 = 'This is a test of the emergency text system'
filename = 'text.txt'
with open(filename, 'w') as f:
    print(test1, file=f, end='')

print('8-2')
with open(filename) as f:
    test2 = f.read()

print(test1 == test2)

print('8-3')

filename = 'books.csv'
s = '''author,book
J R R Tolkien,The Hobbit
Lynne Truss, "Eats, Shoots & Leaves"'''

with open(filename, 'w') as f:
    print(s, file=f, end='')

print('8-4')

import csv

with open(filename) as f:
    dict_reader = csv.DictReader(f)
    for row in dict_reader:
        print(row)

print('8-5')
s = '''title,author,year
The Weirdstone of Brisingamen,Alan Garner,1960
Perdido Street Station,China Méville,2000
Thud!,Terry Pratchett,2005
The Spellman Files,Lisa Lutz,2007
Small Gods,Terry Pratchett,1992'''

with open(filename, 'w') as f:
    print(s, file=f, end='')

print('8-6')

import sqlite3 as sql

dbname = 'books.db'
conn = sql.connect(dbname)
cur = conn.cursor()
cur.execute('''CREATE TABLE book (
title VARCHAR(100),
author VARCHAR(50),
year INT)''')

print('8-7')

ins = 'INSERT INTO book VALUES(?, ?, ?)'
with open(filename) as f:
    dict_reader = csv.DictReader(f)
    for row in dict_reader:
        cur.execute(ins, (row['title'], row['author'], row['year']))

print('8-8')
ins = '''SELECT title FROM book ORDER BY title'''
cur.execute(ins)

for title in cur.fetchall():
    print(title[0])

print('8-9')
cur.execute('''SELECT * FROM book ORDER BY year''')
for row in cur.fetchall():
    print(row)

conn.commit()

cur.close()
conn.close()

print('8-10')

import sqlalchemy as sa

conn = sa.create_engine('sqlite:///{0}'.format(dbname))

rows = conn.execute(ins)

for row in rows:
    print(row[0])

# Redis サーバーはインストールしてないけど、MongoDB はインストール済みだから
# pymongo module を利用して MongoDB を Redis の代わりとして。    
print('8-11')

from pymongo import MongoClient

c = MongoClient(host='localhost')
dbh = c['mydb']

test_doc = {'count': 1, 'name': 'Fester Bestertester'}

dbh.redis.drop()
dbh.redis.insert_one(test_doc)

for doc in dbh.redis.find():
    print(doc)

print('8-12')
dbh.redis.update_one({'name': 'Fester Bestertester'},
                     {'$inc': {'count': 1}})
for doc in dbh.redis.find():
    print(doc)

入出力結果(Terminal, IPython)

$ ./sample.py
8-1
8-2
True
8-3
8-4
{'author': 'J R R Tolkien', 'book': 'The Hobbit'}
{'author': 'Lynne Truss', None: [' Shoots & Leaves"'], 'book': ' "Eats'}
8-5
8-6
8-7
8-8
Perdido Street Station
Small Gods
The Spellman Files
The Weirdstone of Brisingamen
Thud!
8-9
('The Weirdstone of Brisingamen', 'Alan Garner', 1960)
('Small Gods', 'Terry Pratchett', 1992)
('Perdido Street Station', 'China Méville', 2000)
('Thud!', 'Terry Pratchett', 2005)
('The Spellman Files', 'Lisa Lutz', 2007)
8-10
Perdido Street Station
Small Gods
The Spellman Files
The Weirdstone of Brisingamen
Thud!
8-11
{'name': 'Fester Bestertester', '_id': ObjectId('57b9ba59a54d755d38a5d633'), 'count': 1}
8-12
{'name': 'Fester Bestertester', '_id': ObjectId('57b9ba59a54d755d38a5d633'), 'count': 2}
$

0 コメント:

コメントを投稿