「入門Python3」(オライリー)という本の復讐問題の中の、8-5〜8-9(p.271)をやっていて、分からないところがありました。
8-5 次の行を使って、books.csvというCSVファイルを作ろう。
title,author,year
The Wierdstone of Brisingaman,Alen Garner,1960
Perdido Street Station,China Mieville,2000
Thud!,Terry Pratchett,2005
The Spellman Files,Lisa Lutz,2007
Small Gods,Terry Pratchett,1922
8-5は、下記の本の解答どおりでできました。
python
1import csv 2text = '''title,author,year 3The Wierdstone of Brisingaman,Alen Garner,1960 4Perdido Street Station,China Mieville,2000 5Thud!,Terry Pratchett,2005 6The Spellman Files,Lisa Lutz,2007 7Small Gods,Terry Pratchett,1922 8''' 9with open('books.csv', 'wt') as outfile: 10 outfile.write(text)
8-6 sqlite3モジュールを使って、books.dbというSQLiteデータベースを作り、そのなかにtitle(文字列)、author(文字列)、year(整数)というフィールドを持つbookというテーブルを作ろう。
8-6も、下記の本の解答通りでできました。
python
1import sqlite3 2conn = sqlite3.connect('books.db') 3curs = conn.cursor() 4curs.execute('CREATE TABLE book (title VARCHAR(20) PRIMARY KEY, author VARCHAR(20), year INT)')
8-7 books.csvを読み出し、そのデータをbookテーブルに挿入しよう。
8-7も、下記の本の解答通りやって、エラーはでませんでした。
python
1ins_str = 'INSERT INTO book (title, author, year) VALUES(?, ?, ?)' 2with open('books.csv','rt') as infile: 3 books = csv.DictReader(infile) 4 for book in books: 5 curs.execute(ins, (book['title'], book['author'], book['year']))
8-8 bookテーブルのtitle列を選択し、アルファベット順に表示しよう。
8-8は、本の解答によると、
python
1sql = 'select title from book order by title asc' 2for row in curs.execute(sql): 3 print(row)
です。しかし、これでは、
(u'Perdido Street Station',)
(u'Small Gods',)
(u'The Spellman Files',)
(u'The Wierdstone of Brisingaman',)
(u'Thud!',)
と表示されてしまいます。
解答では、
('Perdido Street Station',)
('Small Gods',)
('The Spellman Files',)
('The Wierdstone of Brisingaman',)
('Thud!',)
となっており、uがついていません。
なぜ、私の場合はuがついてしまうのでしょうか?
ユニコードの扱いがどこかでおかしかったのだと思いますが、Sqlite3の時点でおかしかったのではないかと思います。
試しに、
python
1with open("books.csv") as fin: 2 cin = csv.reader(fin) 3 list = [row for row in fin] 4list
を実行してみると、
['title,author,year\n',
'The Wierdstone of Brisingaman,Alen Garner,1960\n',
'Perdido Street Station,China Mieville,2000\n',
'Thud!,Terry Pratchett,2005\n',
'The Spellman Files,Lisa Lutz,2007\n',
'Small Gods,Terry Pratchett,1922\n']
と表示され、
CSVに時点では、uがついていないためです。
なお、Pythonのバージョンは、2.7.11です。
お分かりの方、ご教示頂ければ幸いです。よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2016/01/04 23:25