こんにちは。
巷ではセブ島に行ってプログラミングを習得するというプログラミングスクールがあるそうです。
プログラミングと英語を同時に習得しようというコンセプトだそうです。
果たして成果は出ているのでしょうか…
さてさて今回の目的ですが、プログラミングと英語を同時に習得するという夢のような話を独学でやってみようというチャレンジです。
概要
まず何をするかというと英語の基礎部分である単語を覚えていこうと思います。
学生時代によくやった単語帳をプログラミングで再現してみようという魂胆です。
で、今回はその準備編なので元となる英単語をスクレイピングで取得します。
やること
まず取得したいWebページですが、
ここのサイトのお力添えを借りたいと思います。
中学1年生のページになっていますが、テスト用なので勘弁してください。
筆者の英語力は中1並みということです。
上記サイトから英語とそれに合わせた日本語を取得し、
SQLiteに格納するという作業を行います。
準備
インストールしておくべきモジュール
・requests
・BeautifulSoup
・sqlite3
この3点です。
実装コード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
import requests from bs4 import BeautifulSoup import sqlite3 def CreateDB(dbname): #データベースに接続 con = sqlite3.connect(dbname) cursor = con.cursor() try: #データベース作成 cursor.execute("CREATE TABLE WordList ("\ " id integer primary key autoincrement,"\ " english TEXT ,"\ " japanese TEXT)"\ ) except sqlite3.Error as err: print(err.args[0]) #SQL実行 con.commit() #接続を閉じる con.close() def WordsGet(target_url,dbname): #データベースに接続 con = sqlite3.connect(dbname) cursor = con.cursor() r = requests.get(target_url) soup = BeautifulSoup(r.content, "html.parser") strEngList = soup.find_all("div", attrs={"class": "eng"}) strJpnList = soup.find_all("div", attrs={"class": "jap"}) i=0 for word in strEngList: data = ( word.string, strJpnList[i].string ) print(data) cursor.execute(""" INSERT INTO WordList (english, japanese) VALUES (?, ?) """, data) con.commit() i+=1 #接続を閉じる con.close() filename = 'EnglishWords.sqlite' #初回のみ起動 CreateDB(filename) #データベースに格納 WordsGet("http://www.eigo-duke.com/tango/chu1.html",filename) |
コードの解説
正直解説はあまり必要ないと思いますが、一応しておきます。
1 2 |
strEngList = soup.find_all("div", attrs={"class": "eng"}) strJpnList = soup.find_all("div", attrs={"class": "jap"}) |
beautifulsoupのfind_allで一致するもの全てを検索し、
(“div” attrs={“class”:”eng”})でdivタグの中のclassがengというものを抽出しています。
1 2 3 4 |
data = ( word.string, strJpnList[i].string ) |
ここで抽出したサイト情報の英単語と日本語を1行ずつdataという変数に入れています。
1 2 3 4 |
cursor.execute(""" INSERT INTO WordList (english, japanese) VALUES (?, ?) """, data) con.commit() |
ここでSQL文を発行し、INSERTしています。
commitを忘れると実行されないので注意しましょう。
実行結果
以下のコードを実行して格納されているか確認しましょう。
1 2 3 4 5 6 7 8 9 10 11 |
import sqlite3 filename = 'EnglishWords.sqlite' con = sqlite3.connect(filename) cursor = con.cursor() cursor.execute("select * from WordList") print(cursor.fetchall()) con.close() |
まとめ
今回は準備編ということで、SQLiteにデータをためるだけでしたが、
次回からはデータを使って、英語勉強に向けてプログラミングをします。
コメントを書く