言語処理100本ノック

35. 名詞の連接

名詞の連接(連続して出現する名詞)を最長一致で抽出せよ

import re

sentences = []
with open("D:\\nlp100\\neko.txt.mecab",encoding="UTF-8") as fr:
    line = fr.readline()
    keitaiso = []
    while line:
        if "EOS" in line:
            if len(keitaiso)>0:
                sentences.append(keitaiso)
                keitaiso = []
        else:
            line = re.split(r'[\t,]',line)            
            keitaiso.append({"surface":line[0],"base":line[7],"pos":line[1],"pos1":line[2]})
        line =fr.readline()

rensetu = []
for sentence in sentences:
    for index in range(0,len(sentence)):
        if sentence[index]["pos"] == "名詞":
            rensetu.append(sentence[index]["surface"])
        else:
            if len(rensetu) > 1:
                print(rensetu)
            rensetu = []

 <結果 一部>
['人間', '中']
['一番', '獰悪']
['時', '妙']
['一', '毛']
['その後', '猫']
['一', '度']
['ぷうぷうと', '煙']
['邸', '内']
['三', '毛']
['書生', '以外']
['四', '五', '遍']
['この間', 'おさん']

言語処理100本ノック

34. 「AのB」

2つの名詞が「の」で連結されている名詞句を抽出せよ.

import re

sentences = []
with open("D:\\nlp100\\neko.txt.mecab",encoding="UTF-8") as fr:
    line = fr.readline()
    keitaiso = []
    while line:
        if "EOS" in line:
            if len(keitaiso)>0:
                sentences.append(keitaiso)
                keitaiso = []
        else:
            line = re.split(r'[\t,]',line)            
            keitaiso.append({"surface":line[0],"base":line[7],"pos":line[1],"pos1":line[2]})
        line =fr.readline()

for sentence in sentences:
    for index in range(1,len(sentence) - 1):
        if sentence[index - 1]["pos"] == "名詞" and sentence[index]["surface"] == "の" and sentence[index + 1]["pos"] == "名詞":
            print(sentence[index - 1]["surface"] + sentence[index]["surface"] + sentence[index + 1]["surface"])

<結果>

彼の掌
掌の上
書生の顔
はずの顔
顔の真中
穴の中
書生の掌
掌の裏
何の事
肝心の母親
藁の上
笹原の中
池の前
池の上    

言語処理100本ノック

33. サ変名詞

サ変接続の名詞をすべて抽出せよ.

import re

sentences = []
with open("D:\\nlp100\\neko.txt.mecab",encoding="UTF-8") as fr:
    line = fr.readline()
    keitaiso = []
    while line:
        if "EOS" in line:
            if len(keitaiso)>0:
                sentences.append(keitaiso)
                keitaiso = []
        else:
            line = re.split(r'[\t,]',line)            
            keitaiso.append({"surface":line[0],"base":line[7],"pos":line[1],"pos1":line[2]})
        line =fr.readline()

for sentence in sentences:
    for word in sentence:
        if word["pos1"] == "サ変接続":
            print(word["surface"])

<結果 一部>
見当
記憶
話
装飾
突起
運転
記憶
分別
決心
我慢
餓死
訪問
始末
猶予
遭遇
我慢
記憶
返報
勉強

言語処理100本ノック

32. 動詞の原形

動詞の原形をすべて抽出せよ.

import re

sentences = []
with open("D:\\nlp100\\neko.txt.mecab",encoding="UTF-8") as fr:
    line = fr.readline()
    keitaiso = []
    while line:
        if "EOS" in line:
            if len(keitaiso)>0:
                sentences.append(keitaiso)
                keitaiso = []
        else:
            line = re.split(r'[\t,]',line)            
            keitaiso.append({"surface":line[0],"base":line[7],"pos":line[1],"pos1":line[2]})
        line =fr.readline()

for sentence in sentences:
    for word in sentence:
        if word["pos"] == "動詞":
            print(word["base"])

<結果 一部>
生れる
つく
する
泣く
する
いる
始める
見る
聞く
捕える
煮る
食う
思う
載せる
られる
持ち上げる
られる

言語処理100本ノック

31. 動詞

動詞の表層形をすべて抽出せよ.

import re

sentences = []
with open("D:\\nlp100\\neko.txt.mecab",encoding="UTF-8") as fr:
    line = fr.readline()
    keitaiso = []
    while line:
        if "EOS" in line:
            if len(keitaiso)>0:
                sentences.append(keitaiso)
                keitaiso = []
        else:
            line = re.split(r'[\t,]',line)            
            keitaiso.append({"surface":line[0],"base":line[7],"pos":line[1],"pos1":line[2]})
        line =fr.readline()

for sentence in sentences:
    for word in sentence:
        if word["pos"] == "動詞":
            print(word["surface"])
<結果(一部)>

生れ
つか
し
泣い
し
いる
始め
見
聞く
捕え
煮
食う
思わ
載せ
られ
持ち上げ
られ

言語処理100本ノック

30. 形態素解析結果の読み込み

形態素解析結果(neko.txt.mecab)を読み込むプログラムを実装せよ.ただし,各形態素は表層形(surface),基本形(base),品詞(pos),品詞細分類1(pos1)をキーとするマッピング型に格納し,1文を形態素マッピング型)のリストとして表現せよ.第4章の残りの問題では,ここで作ったプログラムを活用せよ.

import re

sentences = []
with open("D:\\nlp100\\neko.txt.mecab",encoding="UTF-8") as fr:
    line = fr.readline()
    keitaiso = []
    while line:
        if "EOS" in line:
            if len(keitaiso)>0:
                sentences.append(keitaiso)
                keitaiso = []
        else:
            line = re.split(r'[\t,]',line)            
            keitaiso.append({"surface":line[0],"base":line[7],"pos":line[1],"pos1":line[2]})
        line =fr.readline()

print(sentences)

<結果(一部)>

[[{'base': '一', 'pos': '名詞', 'surface': '一', 'pos1': '数'}], [{'base': '\u3000', 'pos': '記号', 'surface': '\u3000', 'pos1': '空白'}], [{'base': '吾輩', 'pos': '名詞', 'surface': '吾輩', 'pos1': '代名詞'}, {'base': 'は', 'pos': '助詞', 'surface': 'は', 'pos1': '係助詞'}, {'base': '猫', 'pos': '名詞', 'surface': '猫', 'pos1': '一般'}, {'base': 'だ', 'pos': '助動詞', 'surface': 'で', 'pos1': '*'}, {'base': 'ある', 'pos': '助動詞', 'surface': 'ある', 'pos1': '*'}, {'base': '。', 'pos': '記号', 'surface': '。', 'pos1': '句点'}], [{'base': '名前', 'pos': '名詞', 'surface': '名前', 'pos1': '一般'}, {'base': 'は', 'pos': '助詞', 'surface': 'は', 'pos1': '係助詞'}, {'base': 'まだ', 'pos': '副詞', 'surface': 'まだ', 'pos1': '助詞類接続'}, {'base': '無い', 'pos': '形容詞', 'surface': '無い', 'pos1': '自立'},

言語処理100本ノック

27. 内部リンクの除去¶

26の処理に加えて,テンプレートの値からMediaWikiの内部リンクマークアップを除去し,テキストに変換せよ(参考: マークアップ早見表).

import json
import re

def wiki_selection():
    with open("D:\\nlp100\\jawiki-country.json",encoding="UTF-8") as fr:
        wiki_line = fr.readline()
        while wiki_line:
            wiki_dic = json.loads(wiki_line)
            if wiki_dic["title"] == "イギリス":
                return wiki_dic["text"]
            wiki_line =fr.readline()

text = wiki_selection()
text = re.sub("<br/>\n", " ",text)
basic_info = {}
for line in re.findall(".* = .*",text):
    line = re.sub(r"'{2,5}",r"",line)
    line = re.sub(r"(\[\[)",r"",line)
    line = re.sub(r"(\]\])",r"",line)
    list = line.split("=")
    basic_info[list[0].lstrip("|")] = list[1]
for k,v in basic_info.items():
    print( k,v)

<結果>

確立年月日1   927年/843年
GDP統計年   2012
略名   イギリス
GDP値元   1兆5478億<ref name
時間帯   ±0
確立形態2   グレートブリテン王国建国<br />(連合法 (1707年)|1707年連合法)
国際電話番号   44
GDP統計年MER   2012
ISO 3166-1   GB / GBR
最大都市   ロンドン
面積値   244,820
人口順位   22
首都   ロンドン
ccTLD   .uk / .gb<ref>使用は.ukに比べ圧倒的少数。</ref>
元首等肩書   イギリスの君主|女王
首相等肩書   イギリスの首相|首相
GDP値   2兆3162億<ref name
通貨コード   GBP
国章画像   ファイル:Royal Coat of Arms of the United Kingdom.svg|85px|イギリスの国章
人口統計年   2011
人口大きさ   1 E7
注記   <references />
建国形態   建国
確立年月日4   1927年
元首等氏名   エリザベス2世
GDP順位   6
公式国名   {{lang|en|United Kingdom of Great Britain and Northern Ireland}}<ref>英語以外での正式国名: *{{lang|gd|An Rìoghachd Aonaichte na Breatainn Mhòr agus Eirinn mu Thuath}}(スコットランド・ゲール語) *{{lang|cy|Teyrnas Gyfunol Prydain Fawr a Gogledd Iwerddon}}(ウェールズ語) *{{lang|ga|Ríocht Aontaithe na Breataine Móire agus Tuaisceart na hÉireann}}(アイルランド語) *{{lang|kw|An Rywvaneth Unys a Vreten Veur hag Iwerdhon Glédh}}(コーンウォール語) *{{lang|sco|Unitit Kinrick o Great Breetain an Northren Ireland}}(スコットランド語) **{{lang|sco|Claught Kängrick o Docht Brätain an Norlin Airlann}}、{{lang|sco|Unitet Kängdom o Great Brittain an Norlin Airlann}}(アルスター・スコットランド語)</ref>
公用語   英語(事実上)
人口密度値   246
人口値   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>
水面積率   1.3%
国旗画像   Flag of the United Kingdom.svg
夏時間   +1
GDP統計年元   2012
国歌   女王陛下万歳|神よ女王陛下を守り給え
確立形態3   グレートブリテン及びアイルランド連合王国建国<br />(連合法 (1800年)|1800年連合法)
国章リンク   (イギリスの国章|国章)
日本語国名   グレートブリテン及び北アイルランド連合王国
面積大きさ   1 E11
確立形態4   現在の国号「グレートブリテン及び北アイルランド連合王国」に変更
首相等氏名   デーヴィッド・キャメロン
通貨   スターリング・ポンド|UKポンド (&pound;)
標語   {{lang|fr|Dieu et mon droit}}<br/>(フランス語:神と私の権利)
GDP値MER   2兆4337億<ref name
確立形態1   イングランド王国/スコットランド王国<br />(両国とも連合法 (1707年)|1707年連合法まで)
面積順位   76
確立年月日2   1707年
確立年月日3   1801年
GDP順位MER   5
GDP/人   36,727<ref name
位置画像   Location_UK_EU_Europe_001.svg