言語処理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"])

<結果>

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