今日はこれの他に、地域日本語教室の支援者向け講座を聞いたり、台湾のドキュメンタリー映画「漢字」を観たりした。そろそろ花粉症の薬をもらいに耳鼻科へ行かなあかん時期やんなあ。めんどいなあ。
前回 の続きです。
言語処理100本ノック #059: S式の解析
59. S式の解析
Stanford Core NLPの句構造解析の結果(S式)を読み込み,文中のすべての名詞句(NP)を表示せよ.入れ子になっている名詞句もすべて表示すること.
解答
S式を読む便利な関数があったりしないのかなーと思ってちょっとググったけど、ないっぽかった。
parse の文字列について、(
をトリガとして関数get_content(引数はタグ以降の文字列)
を使う。この関数は、括弧の数を数えて (TAG content)
の content
を抜き出す。
remove_tags(content_str)
は、S式のタグを全部取り除いて単語のスペース区切りを返すやつ。
# knock_059.py import xml.etree.ElementTree as ET xmlfile = 'nlp.txt.xml' def read_parse(parse): for i_start, c_start in enumerate(parse): if c_start is not '(': continue tag = parse[i_start:].split()[0][1:] content_start = i_start + len(tag) + 2 content = get_content(parse[content_start:]) yield (tag, content) return None def remove_tags(content_str): content_list = [] for s in content_str[:-1].split(): if s[0] == '(': continue content_list.append(s.split(')')[0]) return ' '.join(w for w in content_list) def get_content(rest_parse): bracket_counter = -1 content_str = '' for c_content in rest_parse: if c_content == ')': bracket_counter +=1 elif c_content == '(': bracket_counter -=1 content_str += c_content if bracket_counter == 0: break return remove_tags(content_str) if __name__ == '__main__': tree = ET.parse(xmlfile) root = tree.getroot() for parse in root.findall('./document/sentences/sentence/parse'): for p in list(read_parse(parse.text)): if p[0] in ['NP']: print(p[1])
出力
# $ python knock_059.py >> knock_059.txt (20行目まで) Natural language processing Wikipedia the free encyclopedia Natural language processing -LRB- NLP -RRB- the free encyclopedia Natural language processing NLP a field of computer science , artificial intelligence , and linguistics concerned with the interactions between computers and human -LRB- natural -RRB- languages a field of computer science a field computer science artificial intelligence linguistics concerned with the interactions between computers and human -LRB- natural -RRB- languages linguistics the interactions between computers and human -LRB- natural -RRB- languages the interactions computers and human -LRB- natural -RRB- languages computers human -LRB- natural -RRB- languages such NLP the area of humani-computer interaction