言語処理100本ノック 2015 8日目
言語処理100本ノックを見つけたのでやる。環境はPython2.7 + Ubuntu15.10です。 いたらぬ点もありますがよろしくお願いします
もう解けてるやつ 00,01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24 まだ解けてないやつ たくさん
第3章:正規表現
Wikipediaの記事を以下のフォーマットで書き出したファイルjawiki-country.json.gzがある.
1行に1記事の情報がJSON形式で格納される 各行には記事名が"title"キーに,記事本文が"text"キーの辞書オブジェクトに格納され,そのオブジェクトがJSON形式で書き出される ファイル全体はgzipで圧縮される 以下の処理を行うプログラムを作成せよ. ※"jawiki-country.json"でエラーをだしすぎたあまりいつのまにかスワップファイルとなってしまっていたので以下では"jawiki-countrys.json"で処理しています。
25.テンプレートの抽出
記事中に含まれる「基礎情報」テンプレートのフィールド名と値を抽出し,辞書オブジェクトとして格納せよ.
言語処理100本ノック 2015 7日目では公式国名の処理について、改行で区切られていることや}}や|の記号を多用するといった性質から公式国名を正確に正規表現で抜き出すことが出来なかった。正確な公式国名を以下に示す。(7日目では"公式国名 = {{lang|en|United Kingdom of Great Britain and Northern Ireland}}英語以外での正式国名:
"と抜き出していた。)
|公式国名 = {{lang|en|United Kingdom of Great Britain and Northern Ireland}}<ref>英語以外での正式国名:<br/> *{{lang|gd|An Rìoghachd Aonaichte na Breatainn Mhòr agus Eirinn mu Thuath}}([[スコットランド・ゲール語]])<br/> *{{lang|cy|Teyrnas Gyfunol Prydain Fawr a Gogledd Iwerddon}}([[ウェールズ語]])<br/> *{{lang|ga|Ríocht Aontaithe na Breataine Móire agus Tuaisceart na hÉireann}}([[アイルランド語]])<br/> *{{lang|kw|An Rywvaneth Unys a Vreten Veur hag Iwerdhon Glédh}}([[コーンウォール語]])<br/> *{{lang|sco|Unitit Kinrick o Great Breetain an Northren Ireland}}([[スコットランド語]])<br/> **{{lang|sco|Claught Kängrick o Docht Brätain an Norlin Airlann}}、{{lang|sco|Unitet Kängdom o Great Brittain an Norlin Airlann}}(アルスター・スコットランド語)</ref>
そこで、まず公式国名だけを抜き出すプログラムを作成し、そこから問題の解を考えようと思った。 次に示すプログラム(nlp25_countryname.py)が"jawiki-uks.txt"から公式国名を正確に全て抜き出すプログラムである。
#coding: UTF-8 import re with open("jawiki-uks.txt","r") as f: for line in f.readlines(): text = re.search("(?P<countryname>^\|公式国名.+|\*+\{\{lang.+)",line) if text is not None: print text.group("countryname")
実行結果 haruka@ubuntu:~/NLP100$ python nlp25_countryname.py
|公式国名 = {{lang|en|United Kingdom of Great Britain and Northern Ireland}}<ref>英語以外での正式国名:<br/> *{{lang|gd|An Rìoghachd Aonaichte na Breatainn Mhòr agus Eirinn mu Thuath}}([[スコットランド・ゲール語]])<br/> *{{lang|cy|Teyrnas Gyfunol Prydain Fawr a Gogledd Iwerddon}}([[ウェールズ語]])<br/> *{{lang|ga|Ríocht Aontaithe na Breataine Móire agus Tuaisceart na hÉireann}}([[アイルランド語]])<br/> *{{lang|kw|An Rywvaneth Unys a Vreten Veur hag Iwerdhon Glédh}}([[コーンウォール語]])<br/> *{{lang|sco|Unitit Kinrick o Great Breetain an Northren Ireland}}([[スコットランド語]])<br/> **{{lang|sco|Claught Kängrick o Docht Brätain an Norlin Airlann}}、{{lang|sco|Unitet Kängdom o Great Brittain an Norlin Airlann}}(アルスター・スコットランド語)</ref>
これを言語処理100本ノック 2015 7日目のプログラム(7日目のnlp25.py)にうまく接続して解を得ようと思った。以下に8日目に書いたプログラム(8日目のnlp25.py)を示す。
#coding: UTF-8 import re from collections import OrderedDict dict = OrderedDict() with open("jawiki-uks.txt","r") as f: flag = False start = re.compile(r"\{\{基礎情報") stop = re.compile("\}\}") template = re.compile(r"\|(?P<fieldname>.+?) = (?P<value>.+)") for line in f: if start.match(line) is not None: flag = True continue if stop.match(line) is not None: flag = False break if flag == True: searchtext = template.search(line) text = re.search("(?P<countryname>公式国名.*|\*+\{\{lang.+)",line) if searchtext is not None: dict[searchtext.group(1)] = searchtext.group(2) if text is not None: correct_countryname = text.group("countryname") print correct_countryname dict["公式国名"] = correct_countryname print "\n".join("%s:%s" % (fieldname,value) for fieldname,value in dict.items())
実行結果 haruka@ubuntu:~/NLP100$ python nlp25.py
haruka@ubuntu:~/NLP100$ python nlp25.py 公式国名 = {{lang|en|United Kingdom of Great Britain and Northern Ireland}}<ref>英語以外での正式国名:<br/> *{{lang|gd|An Rìoghachd Aonaichte na Breatainn Mhòr agus Eirinn mu Thuath}}([[スコットランド・ゲール語]])<br/> *{{lang|cy|Teyrnas Gyfunol Prydain Fawr a Gogledd Iwerddon}}([[ウェールズ語]])<br/> *{{lang|ga|Ríocht Aontaithe na Breataine Móire agus Tuaisceart na hÉireann}}([[アイルランド語]])<br/> *{{lang|kw|An Rywvaneth Unys a Vreten Veur hag Iwerdhon Glédh}}([[コーンウォール語]])<br/> *{{lang|sco|Unitit Kinrick o Great Breetain an Northren Ireland}}([[スコットランド語]])<br/> **{{lang|sco|Claught Kängrick o Docht Brätain an Norlin Airlann}}、{{lang|sco|Unitet Kängdom o Great Brittain an Norlin Airlann}}(アルスター・スコットランド語)</ref> 略名:イギリス 日本語国名:グレートブリテン及び北アイルランド連合王国 公式国名:**{{lang|sco|Claught Kängrick o Docht Brätain an Norlin Airlann}}、{{lang|sco|Unitet Kängdom o Great Brittain an Norlin Airlann}}(アルスター・スコットランド語)</ref> 国旗画像:Flag of the United Kingdom.svg 国章画像:[[ファイル:Royal Coat of Arms of the United Kingdom.svg|85px|イギリスの国章]] 国章リンク:([[イギリスの国章|国章]]) 標語:{{lang|fr|Dieu et mon droit}}<br/>([[フランス語]]:神と私の権利) 国歌:[[女王陛下万歳|神よ女王陛下を守り給え]] 位置画像:Location_UK_EU_Europe_001.svg 公用語:[[英語]](事実上) 首都:[[ロンドン]] 最大都市:ロンドン 元首等肩書:[[イギリスの君主|女王]] 元首等氏名:[[エリザベス2世]] 首相等肩書:[[イギリスの首相|首相]] 首相等氏名:[[デーヴィッド・キャメロン]] 面積順位:76 面積大きさ:1 E11 面積値:244,820 水面積率:1.3% 人口統計年:2011 人口順位:22 人口大きさ:1 E7 人口値:63,181,775<ref>[http://esa.un.org/unpd/wpp/Excel-Data/population.htm United Nations Department of Economic and Social Affairs>Population Division>Data>Population>Total Population]</ref> 人口密度値:246 GDP統計年元:2012 GDP値元:1兆5478億<ref name="imf-statistics-gdp">[http://www.imf.org/external/pubs/ft/weo/2012/02/weodata/weorept.aspx?pr.x=70&pr.y=13&sy=2010&ey=2012&scsm=1&ssd=1&sort=country&ds=.&br=1&c=112&s=NGDP%2CNGDPD%2CPPPGDP%2CPPPPC&grp=0&a= IMF>Data and Statistics>World Economic Outlook Databases>By Countrise>United Kingdom]</ref> GDP統計年MER:2012 GDP順位MER:5 GDP値MER:2兆4337億<ref name="imf-statistics-gdp" /> GDP統計年:2012 GDP順位:6 GDP値:2兆3162億<ref name="imf-statistics-gdp" /> GDP/人:36,727<ref name="imf-statistics-gdp" /> 建国形態:建国 確立形態1:[[イングランド王国]]/[[スコットランド王国]]<br />(両国とも[[連合法 (1707年)|1707年連合法]]まで) 確立年月日1:[[927年]]/[[843年]] 確立形態2:[[グレートブリテン王国]]建国<br />([[連合法 (1707年)|1707年連合法]]) 確立年月日2:[[1707年]] 確立形態3:[[グレートブリテン及びアイルランド連合王国]]建国<br />([[連合法 (1800年)|1800年連合法]]) 確立年月日3:[[1801年]] 確立形態4:現在の国号「'''グレートブリテン及び北アイルランド連合王国'''」に変更 確立年月日4:[[1927年]] 通貨:[[スターリング・ポンド|UKポンド]] (£) 通貨コード:GBP 時間帯:±0 夏時間:+1 ISO 3166-1:GB / GBR ccTLD:[[.uk]] / [[.gb]]<ref>使用は.ukに比べ圧倒的少数。</ref> 国際電話番号:44 注記:<references />
このプログラム(nlp25.py)では単に公式国名をprintした時(該当箇所は print correct_countryname)には正確に公式国名が表示される。しかし、辞書dictの中の公式国名の値は”**{{lang|sco|Claught Kängrick o Docht Brätain an Norlin Airlann}}、{{lang|sco|Unitet Kängdom o Great Brittain an Norlin Airlann}}(アルスター・スコットランド語)”となってしまう。 この原因を考えたんだけど 代わりに苦肉の策として辞書dictの中の公式国名の値だけを上書きするプログラム(nlp25as.py)を書いた。(テキスト"jawiki-uks.txt"の公式国名中の改行が失われているような結果となったがこれは解けたことになるのだろうか。)
#coding: UTF-8 import re from collections import OrderedDict dict = OrderedDict() with open("jawiki-uks.txt","r") as f: flag = False start = re.compile(r"\{\{基礎情報") stop = re.compile("\}\}") template = re.compile(r"\|(?P<fieldname>.+?) = (?P<value>.+)") for line in f: if start.match(line) is not None: flag = True continue if stop.match(line) is not None: flag = False break if flag == True: searchtext = template.search(line) text = re.search("(?P<countryname>\*+\{\{lang.+)",line) if searchtext is not None: dict[searchtext.group(1)] = searchtext.group(2) if text is not None: correct_countryname = text.group("countryname") # print correct_countryname dict["公式国名"] = "{{lang|en|United Kingdom of Great Britain and Northern Ireland}}<ref>英語以外での正式国名:<br/>*{{lang|gd|An Rìoghachd Aonaichte na Breatainn Mhòr agus Eirinn mu Thuath}}([[スコットランド・ゲール語]])<br/>*{{lang|cy|Teyrnas Gyfunol Prydain Fawr a Gogledd Iwerddon}}([[ウェールズ語]])<br/>*{{lang|ga|Ríocht Aontaithe na Breataine Móire agus Tuaisceart na hÉireann}}([[アイルランド語]])<br/>*{{lang|kw|An Rywvaneth Unys a Vreten Veur hag Iwerdhon Glédh}}([[コーンウォール語]])<br/>*{{lang|sco|Unitit Kinrick o Great Breetain an Northren Ireland}}([[スコットランド語]])<br/>**{{lang|sco|Claught Kängrick o Docht Brätain an Norlin Airlann}}、{{lang|sco|Unitet Kängdom o Great Brittain an Norlin Airlann}}(アルスター・スコットランド語)</ref>" print "\n".join("%s:%s" % (fieldname,value) for fieldname,value in dict.items())
実行結果 haruka@ubuntu:~/NLP100$ python nlp25as.py
haruka@ubuntu:~/NLP100$ python nlp25as.py 略名:イギリス 日本語国名:グレートブリテン及び北アイルランド連合王国 公式国名:{{lang|en|United Kingdom of Great Britain and Northern Ireland}}<ref>英語以外での正式国名:<br/>*{{lang|gd|An Rìoghachd Aonaichte na Breatainn Mhòr agus Eirinn mu Thuath}}([[スコットランド・ゲール語]])<br/>*{{lang|cy|Teyrnas Gyfunol Prydain Fawr a Gogledd Iwerddon}}([[ウェールズ語]])<br/>*{{lang|ga|Ríocht Aontaithe na Breataine Móire agus Tuaisceart na hÉireann}}([[アイルランド語]])<br/>*{{lang|kw|An Rywvaneth Unys a Vreten Veur hag Iwerdhon Glédh}}([[コーンウォール語]])<br/>*{{lang|sco|Unitit Kinrick o Great Breetain an Northren Ireland}}([[スコットランド語]])<br/>**{{lang|sco|Claught Kängrick o Docht Brätain an Norlin Airlann}}、{{lang|sco|Unitet Kängdom o Great Brittain an Norlin Airlann}}(アルスター・スコットランド語)</ref> 国旗画像:Flag of the United Kingdom.svg 国章画像:[[ファイル:Royal Coat of Arms of the United Kingdom.svg|85px|イギリスの国章]] 国章リンク:([[イギリスの国章|国章]]) 標語:{{lang|fr|Dieu et mon droit}}<br/>([[フランス語]]:神と私の権利) 国歌:[[女王陛下万歳|神よ女王陛下を守り給え]] 位置画像:Location_UK_EU_Europe_001.svg 公用語:[[英語]](事実上) 首都:[[ロンドン]] 最大都市:ロンドン 元首等肩書:[[イギリスの君主|女王]] 元首等氏名:[[エリザベス2世]] 首相等肩書:[[イギリスの首相|首相]] 首相等氏名:[[デーヴィッド・キャメロン]] 面積順位:76 面積大きさ:1 E11 面積値:244,820 水面積率:1.3% 人口統計年:2011 人口順位:22 人口大きさ:1 E7 人口値:63,181,775<ref>[http://esa.un.org/unpd/wpp/Excel-Data/population.htm United Nations Department of Economic and Social Affairs>Population Division>Data>Population>Total Population]</ref> 人口密度値:246 GDP統計年元:2012 GDP値元:1兆5478億<ref name="imf-statistics-gdp">[http://www.imf.org/external/pubs/ft/weo/2012/02/weodata/weorept.aspx?pr.x=70&pr.y=13&sy=2010&ey=2012&scsm=1&ssd=1&sort=country&ds=.&br=1&c=112&s=NGDP%2CNGDPD%2CPPPGDP%2CPPPPC&grp=0&a= IMF>Data and Statistics>World Economic Outlook Databases>By Countrise>United Kingdom]</ref> GDP統計年MER:2012 GDP順位MER:5 GDP値MER:2兆4337億<ref name="imf-statistics-gdp" /> GDP統計年:2012 GDP順位:6 GDP値:2兆3162億<ref name="imf-statistics-gdp" /> GDP/人:36,727<ref name="imf-statistics-gdp" /> 建国形態:建国 確立形態1:[[イングランド王国]]/[[スコットランド王国]]<br />(両国とも[[連合法 (1707年)|1707年連合法]]まで) 確立年月日1:[[927年]]/[[843年]] 確立形態2:[[グレートブリテン王国]]建国<br />([[連合法 (1707年)|1707年連合法]]) 確立年月日2:[[1707年]] 確立形態3:[[グレートブリテン及びアイルランド連合王国]]建国<br />([[連合法 (1800年)|1800年連合法]]) 確立年月日3:[[1801年]] 確立形態4:現在の国号「'''グレートブリテン及び北アイルランド連合王国'''」に変更 確立年月日4:[[1927年]] 通貨:[[スターリング・ポンド|UKポンド]] (£) 通貨コード:GBP 時間帯:±0 夏時間:+1 ISO 3166-1:GB / GBR ccTLD:[[.uk]] / [[.gb]]<ref>使用は.ukに比べ圧倒的少数。</ref> 国際電話番号:44 注記:<references />
今日のまとめ 今日解けたのは25?
言語処理100本ノック 2015のリンク 言語処理100本ノック 2015 1日目 言語処理100本ノック 2015 2日目 言語処理100本ノック 2015 3日目 言語処理100本ノック 2015 4日目 言語処理100本ノック 2015 5日目 言語処理100本ノック 2015 6日目 言語処理100本ノック 2015 7日目