-
Notifications
You must be signed in to change notification settings - Fork 5
/
query.lisp
79 lines (61 loc) · 2.17 KB
/
query.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
(in-package :cl-conllu)
(defparameter *deprels* '(acl acl-part acl-relcl
advcl advmod amod
aux aux-pass
case dep det cc ccomp conj
appos cop csubj
discourse dislocated expl
compound fixed flat flat-foreign flat-name
iobj mark
nmod nmod-npmod nmod-tmod nummod
nsubj nsubj-pass
obj obl obl-agent
orphan parataxis
punct reparandum
xcomp vocative))
(defun children (tks id)
(remove-if-not (lambda (tk) (equal (cl-conllu:token-head tk) id)) tks))
(defun r~ (relation query1 query2 &key tks)
(let ((list1 (eval-query query1 :tks tks))
(list2 (eval-query query2 :tks tks))
(rel (string-upcase (substitute #\: #\- (symbol-name relation)))))
(remove-if-not (lambda (tk)
(some (lambda (child)
(equal (string-upcase (token-deprel child)) rel))
(children list2 (cl-conllu:token-id tk))))
list1)))
(defun t~ (slot string &key tks)
(remove-if-not (lambda (tk)
(cl-ppcre:scan string (slot-value tk slot)))
tks))
(defun or% (query1 query2 &key tks)
(let ((list1 (eval-query query1 :tks tks))
(list2 (eval-query query2 :tks tks)))
(union list1 list2)))
(defun and% (query1 query2 &key tks)
(let ((list1 (eval-query query1 :tks tks))
(list2 (eval-query query2 :tks tks)))
(intersection list1 list2)))
(defun eval-query (expression &key tks)
(let ((op (intern (symbol-name (car expression)) :cl-conllu)))
(cond ((member op *deprels*)
(destructuring-bind (deprel arg1 arg2)
expression
(declare (ignore deprel))
(funcall #'r~ op arg1 arg2 :tks tks)))
((member op '(upostag lemma form feats misc xpostag))
(destructuring-bind (field value)
expression
(declare (ignore field))
(funcall #'t~ op value :tks tks)))
((member op '(or and))
(destructuring-bind (op arg1 arg2)
expression
(funcall (getf '(or or% and and%) op) arg1 arg2 :tks tks)))
(t (error "Invalid query.")))))
(defun query (query sentences)
(remove-if-not (lambda (s)
(eval-query query :tks (cl-conllu:sentence-tokens s)))
sentences))
(defun query-as-json (a-query sentences)
(yason:encode (mapcar #'sentence-hash-table (query a-query sentences))))