自作関数のimportとその利用¶
- ここまで扱ってきた処理を毎回行うとそれだけ時間がかかりますので、パッケージとしてまとめたのでその利用方法を示します。
- 自作関数は以下です。
text_to_set_w: 文(文字列)を入力すると単語の点集合と辺集合を返します。text_to_set_i: 文(文字列)を入力すると出現順序の点集合と辺集合を返します。text_to_set_dep: 文(文字列)を入力すると依存関係の点集合と辺集合を返します。set_to_graph: 文の点集合と辺集合を入力するとグラフを返します。set_to_degseq: 文の点集合と辺集合を入力すると次数列を返します。degseq_to_graphcent: 文の次数列を入力するとグラフ中心性を返します。sent_to_add: 文(文字列)を入力すると平均依存距離(average dependency distance)を返します。tree_flatness: 文(文字列)を入力すると木の平坦さを返します。set_to_M: 文の点集合と辺集合(出現順序)を入力すると、隣接行列、次数行列、グラフラプラシアンを返します。edit_dist: 2つのリスト(文字列)を入力すると、その編集距離を返します。
- 以下のようにimportしてください。
In [1]:
import sys
sys.path.append("../")
from common import utils
- 自作関数の使い方を以下に示します。
text_to_set_w
In [2]:
text = "Hiroshima is famous for oysters"
V,E = utils.text_to_set_w(text)
V,E
Out[2]:
(['Hiroshima_0', 'is_1', 'famous_2', 'for_3', 'oysters_4'], [['is_1', 'Hiroshima_0'], ['is_1', 'famous_2'], ['famous_2', 'for_3'], ['for_3', 'oysters_4']])
text_to_set_i
In [3]:
text = "Hiroshima is famous for oysters"
V,E = utils.text_to_set_i(text)
V,E
Out[3]:
([0, 1, 2, 3, 4], [[1, 0], [1, 2], [2, 3], [3, 4]])
text_to_set_dep
In [4]:
text = "Hiroshima is famous for oysters"
V,E = utils.text_to_set_dep(text)
V,E
Out[4]:
(['nsubj_0', 'ROOT_1', 'acomp_2', 'prep_3', 'pobj_4'], [['ROOT_1', 'nsubj_0'], ['ROOT_1', 'acomp_2'], ['acomp_2', 'prep_3'], ['prep_3', 'pobj_4']])
set_to_graph
In [5]:
text = "Please get home safe."
V,E = utils.text_to_set_w(text)
g = utils.set_to_graph(V,E)
g
Out[5]:
set_to_degseq
In [3]:
text = "Hiroshima is famous for oysters"
V,E = utils.text_to_set_w(text)
utils.set_to_degseq(V,E)
Out[3]:
[2, 2, 2, 1, 1]
degseq_to_graphcent
In [3]:
text = "Hiroshima is famous for oysters"
V,E = utils.text_to_set_w(text)
A = utils.set_to_degseq(V,E)
utils.degseq_to_graphcent(A)
Out[3]:
0.16666666666666666
sent_to_add
In [6]:
text = "A humpback whale has made one of the longest and most unusual migrations ever recorded, possibly driven by climate change, scientists say."
a = utils.sent_to_add(text)
a
Out[6]:
3.4583333333333335
tree_flatness
In [7]:
text = "You should try it too."
f = utils.tree_flatness(text)
f
Out[7]:
5
set_to_M
In [8]:
text = "Hiroshima is famous for oysters"
V,E = utils.text_to_set_i(text)
G_adj,G_deg,G_lap = utils.set_to_M(V,E)
G_adj
Out[8]:
array([[0., 1., 0., 0., 0.],
[1., 0., 1., 0., 0.],
[0., 1., 0., 1., 0.],
[0., 0., 1., 0., 1.],
[0., 0., 0., 1., 0.]])
edit_dist
In [9]:
a = "とまと"
b = "とまれ"
utils.edit_dist(a,b)
Out[9]:
1