開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- Python 3.5 (プログラミング言語)
Introducing Python: Modern Computing in Simple Packages (Bill Lubanovic (著)、 O'Reilly Media)のChapter 8(Data Has to Go Somewhere)、Things to Do 8.1-12.を取り組んでみる。
Things to Do 8.1-12.
コード(Emacs)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
print('1.')
test1 = 'This is a test of the emergency text system'
with open('test.txt', 'w') as f:
print(test1, file=f, end='')
print('2.')
with open('test.txt', 'r') as f:
test2 = f.read()
print(test1 == test2)
print('3.')
lines = '''author,book
J R RTolkien,The Hobbit
Lynne Truss,"Eats,Shooots & Leaves"
'''
with open('books.csv', 'w') as f:
print(lines, file=f, end='')
print('4.')
import csv
with open('books.csv') as f:
books = csv.DictReader(f)
for book in books:
print(book)
print('5.')
lines = '''title,author,year
The Weirdstone of Brisingamen,Alan Garner,1960
Perdido Street Station,China Miéville,2000
thud!,Terry Pratchett,2005
The Spellman Files,Lisa Lutz,2007
Small Gods,Terry Pratchett,1992
'''
with open('books.csv', 'w') as f:
print(lines, file=f, end='')
print('6.')
import sqlite3 as sql
import os
if os.path.isfile('books.db'):
os.remove('books.db')
con = sql.connect('books.db')
cur = con.cursor()
cur.execute('''CREATE TABLE books
(title VARCHAR(20) PRIMARY KEY,
author VARCHAR(20),
year INT)
''')
con.commit()
print('7.')
ins = 'INSERT INTO books (title, author, year) VALUES(?, ?, ?)'
with open('books.csv') as f:
books = csv.DictReader(f)
for book in books:
cur.execute(ins, (book['title'], book['author'], book['year']))
con.commit()
print('8.')
for title in con.execute('SELECT title FROM books ORDER BY title'):
print(title[0])
print('9.')
for row in con.execute('SELECT * FROM books ORDER BY year'):
print(row)
print('10.')
import sqlalchemy as sa
con = sa.create_engine('sqlite:///books.db')
for title in con.execute('SELECT title FROM books ORDER BY title'):
print(title[0])
print('11.')
import redis
con = redis.Redis()
con.hmset('test', dict(count=1, name='Fester Bestertester'))
print(con.hkeys('test'))
print('12.')
print(con.hgetall('test'))
con.hincrby('test', 'count', 1)
print(con.hgetall('test'))
入出力結果(Terminal, IPython)
$ sudo port load redis
$ ./sample1.py
1.
2.
True
3.
4.
{'book': 'The Hobbit', 'author': 'J R RTolkien'}
{'book': 'Eats,Shooots & Leaves', 'author': 'Lynne Truss'}
5.
6.
7.
8.
Perdido Street Station
Small Gods
The Spellman Files
The Weirdstone of Brisingamen
thud!
9.
('The Weirdstone of Brisingamen', 'Alan Garner', 1960)
('Small Gods', 'Terry Pratchett', 1992)
('Perdido Street Station', 'China Miéville', 2000)
('thud!', 'Terry Pratchett', 2005)
('The Spellman Files', 'Lisa Lutz', 2007)
10.
Perdido Street Station
Small Gods
The Spellman Files
The Weirdstone of Brisingamen
thud!
11.
[b'count', b'name']
12.
{b'name': b'Fester Bestertester', b'count': b'1'}
{b'name': b'Fester Bestertester', b'count': b'2'}
$ sudo port unload redis
$
0 コメント:
コメントを投稿