forked from zalio/word-problem-solver-thesis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools__for_qg-Iztech.py
2125 lines (1975 loc) · 105 KB
/
tools__for_qg-Iztech.py
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# encoding: utf-8
# Practical Natural Language Processing Tools (practNLPTools-lite):
# Combination of Senna and Stanford dependency Extractor
# Copyright (C) 2017 PractNLP-lite Project
# Current Author: Jawahar S <[email protected]>
# URL: https://jawahar273.gitbooks.io (or) https://github.com/jawahar273
from __future__ import generators, print_function, unicode_literals
import subprocess
import json
import utils
import tree_kernel
import subprocess
import os
import re
import spacy
from platform import architecture, system
from allennlp.predictors import Predictor
import pandas as pd
from allennlp.service.predictors import SemanticRoleLabelerPredictor
#from pattern.en import conjugate, lemma, lexeme,PRESENT,SG
try:
from colorama import init
from colorama.Fore import RED, BLUE
init(autoreset=True)
except ImportError:
RED = " "
BLUE = " "
class Annotator:
"""
:param str senna_dir: path where is located
:param str dep_model: Stanford dependencie mode
:param str stp_dir: path of stanford parser jar
:param str raise_e: raise exception if stanford-parser.jar
is not found
"""
def __init__(self, senna_dir='', stp_dir='',
dep_model='edu.stanford.nlp.trees.'
'EnglishGrammaticalStructure',
raise_e=False):
"""
init function of Annotator class
"""
self.senna_path = ''
self.dep_par_path = ''
if not senna_dir:
if 'SENNA' in os.environ:
self.senna_path = os.path.normpath(os.environ['SENNA'])
self.senna_path + os.path.sep
exe_file_2 = self.get_senna_bin(self.senna_path)
if not os.path.isfile(exe_file_2):
raise OSError(RED +
"Senna executable expected at %s or"
" %s but not found"
% (self.senna_path, exe_file_2))
elif senna_dir.startswith('.'):
self.senna_path = os.path.realpath(senna_dir) + os.path.sep
else:
self.senna_path = senna_dir.strip()
self.senna_path = self.senna_path.rstrip(os.path.sep) + os.path.sep
if not stp_dir:
import pntl.tools as Tfile
self.dep_par_path = Tfile.__file__.rsplit(os.path.sep, 1)[0] + os.path.sep
self.check_stp_jar(self.dep_par_path, raise_e=True)
else:
self.dep_par_path = stp_dir + os.path.sep
self.check_stp_jar(self.dep_par_path, raise_e)
self.dep_par_model = dep_model
# print(dep_model)
self.default_jar_cli = ['java', '-cp', 'stanford-parser.jar',
self.dep_par_model,
'-treeFile', 'in.parse', '-collapsed']
self.print_values()
def print_values(self):
""" displays the current set of values
such as SENNA location, stanford parser jar,
jar command interface
"""
print("**" * 50)
print("default values:\nsenna path:\n", self.senna_path,
"\nDependencie parser:\n", self.dep_par_path)
# print(self.default_jar_cli)
print("Stanford parser clr", " ".join(self.default_jar_cli))
print("**" * 50)
def check_stp_jar(self, path, raise_e=False, _rec=True):
"""Check the stanford parser is present in the given directions
and nested searching will be added in futurwork
:param str path: path of where the stanford parser is present
:param bool raise_e: to raise exception with user
wise and default `False` don't raises exception
:return: given path if it is valid one or return boolean `False` or
if raise FileNotFoundError on raise_exp=True
:rtype: bool
"""
gpath = path
path = os.listdir(path)
file_found = False
for file in path:
if file.endswith(".jar"):
if file.startswith("stanford-parser"):
file_found = True
if not file_found:
# need to check the install dir for stanfor parser
if _rec:
import pntl
path_ = os.path.split(pntl.__file__)[0]
self.check_stp_jar(path_, raise_e, _rec=False)
if raise_e:
raise FileNotFoundError(RED + "`stanford-parser.jar` is "
"not"
" found in the path \n"
"`{}` \n"
"To know about more about the issues,"
"got to this given link ["
"http://pntl.readthedocs.io/en/"
"latest/stanford_installing_"
"issues.html] \n User "
"`pntl -I true` to downlard "
"needed file automatically."
.format(gpath))
return file_found
@property
def stp_dir(self):
"""The return the path of stanford parser jar location
and set the path for Dependency Parse at run time(
this is python @property)
"""
return self.dep_par_path
@stp_dir.setter
def stp_dir(self, val):
if os.path.isdir(val):
self.dep_par_path = val + os.path.sep
@property
def senna_dir(self):
"""The return the path of senna location
and set the path for senna at run time(this is python @property)
:rtype: string
"""
return self.senna_path
@senna_dir.setter
def senna_dir(self, val):
if os.path.isdir(val):
self.senna_path = val + os.path.sep
@property
def jar_cli(self):
"""
The return cli for standford-parser.jar(this is python @property)
:rtype: string
"""
return " ".join(self.default_jar_cli)
@jar_cli.setter
def jar_cli(self, val):
self.default_jar_cli = val.split()
def get_senna_bin(self, os_name):
"""
get the current os executable binary file.
:param str os_name: os name like Linux, Darwin, Windows
:return: the corresponding exceutable object file of senna
:rtype: str
"""
if os_name == 'Linux':
bits = architecture()[0]
if bits == '64bit':
executable = 'senna-linux64'
elif bits == '32bit':
executable = 'senna-linux32'
else:
executable = 'senna'
elif os_name == 'Darwin':
executable = 'senna-osx'
elif os_name == 'Windows':
executable = 'senna-win32.exe'
return self.senna_path + executable
def get_senna_tag_batch(self, sentences):
"""
Communicates with senna through lower level communiction(sub process)
and converted the console output(default is file writing).
On batch processing each end is add with new line.
:param list sentences: list of sentences for batch processes
:rtype: str
"""
input_data = ""
for sentence in sentences:
input_data += sentence + "\n"
input_data = input_data[:-1]
package_directory = os.path.dirname(self.senna_path)
os_name = system()
executable = self.get_senna_bin(os_name)
senna_executable = os.path.join(package_directory, executable)
cwd = os.getcwd()
os.chdir(package_directory)
pipe = subprocess.Popen(senna_executable,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=True)
senna_stdout = pipe.communicate(input=input_data.encode('utf-8'))[0]
os.chdir(cwd)
return senna_stdout.decode().split("\n\n")[0:-1]
@classmethod
def help_conll_format(cls):
"""With the help of this method, detail of senna
arguments are displayed
"""
return cls.get_conll_format.__doc__.split("\n\n")[1]
def get_conll_format(self, sentence, options='-srl -pos -ner -chk -psg'):
"""Communicates with senna through lower level communiction
(sub process) and converted the console output(default is file writing)
with CoNLL format and argument to be in `options` pass
:param str or list: list of sentences for batch processes
:param options list: list of arguments
+--------------+-----------------------------------------------+
| options | desc |
+==============+===============================================+
| -verbose | Display model informations (on the standard |
| | error output, so it does not mess up the tag |
| | outputs). |
+--------------+-----------------------------------------------+
| -notokentags | Do not output tokens (first output column). |
+--------------+-----------------------------------------------+
| -offsettags | Output start/end character offset (in the |
| | sentence), for each token. |
+--------------+-----------------------------------------------+
| -iobtags | Output IOB tags instead of IOBES. |
+--------------+-----------------------------------------------+
| -brackettags | Output ‘bracket’ tags instead of IOBES. |
+--------------+-----------------------------------------------+
| -path | Specify the path to the SENNA data and hash |
| | directories, if you do not run SENNA in its |
| | original directory. The path must end by “/”. |
+--------------+-----------------------------------------------+
| -usrtokens | Use user’s tokens (space separated) instead |
| | of SENNA tokenizer. |
+--------------+-----------------------------------------------+
| -posvbs | Use verbs outputed by the POS tagger instead |
| | of SRL style verbs for SRL task. You might |
| | want to use this, as the SRL training task |
| | ignore some verbs (many “be” and “have”) |
| | which might be not what you want. |
+--------------+-----------------------------------------------+
| -usrvbs | Use user’s verbs (given in ) instead of SENNA |
| | verbs for SRL task. The file must contain one |
| | line per token, with an empty line between |
| | each sentence. A line which is not a “-” |
| | corresponds to a verb. |
+--------------+-----------------------------------------------+
| -pos | Instead of outputing tags for all tasks, |
| | SENNA will output tags for the specified (one |
| | or more) tasks. |
+--------------+-----------------------------------------------+
| -chk | Instead of outputing tags for all tasks, |
| | SENNA will output tags for the specified (one |
| | or more) tasks. |
+--------------+-----------------------------------------------+
| -ner | Instead of outputing tags for all tasks, |
| | SENNA will output tags for the specified (one |
| | or more) tasks. |
+--------------+-----------------------------------------------+
| -srl | Instead of outputing tags for all tasks, |
| | SENNA will output tags for the specified (one |
| | or more) tasks. |
+--------------+-----------------------------------------------+
| -psg | Instead of outputing tags for all tasks, |
| | SENNA will output tags for the specified (one |
| | or more) tasks. |
+--------------+-----------------------------------------------+
:return: senna tagged output
:rtype: str
"""
if isinstance(options, str):
options = options.strip().split()
input_data = sentence
package_directory = os.path.dirname(self.senna_path)
os_name = system()
executable = self.get_senna_bin(os_name)
senna_executable = os.path.join(executable)
# print("testing dir", executable, package_directory)
cwd = os.getcwd()
os.chdir(package_directory)
args = [senna_executable]
args.extend(options)
pipe = subprocess.Popen(args,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=True)
senna_stdout = pipe.communicate(input=" ".join(input_data)
.encode('utf-8'))[0]
os.chdir(cwd)
return senna_stdout.decode("utf-8").strip()
def get_senna_tag(self, sentence):
"""
Communicates with senna through lower level communiction(sub process)
and converted the console output(default is file writing)
:param str/list listsentences : list of sentences for batch processes
:return: senna tagged output
:rtype: str
"""
input_data = sentence
package_directory = os.path.dirname(self.senna_path)
# print("testing dir",self.dep_par_path, package_directory)
os_name = system()
executable = self.get_senna_bin(os_name)
senna_executable = os.path.join(package_directory, executable)
cwd = os.getcwd()
os.chdir(package_directory)
pipe = subprocess.Popen(senna_executable,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=True)
senna_stdout = pipe.communicate(input=" ".join(input_data)
.encode('utf-8'))[0]
os.chdir(cwd)
return senna_stdout
def get_dependency(self, parse):
"""
Change to the Stanford parser direction and process the works
:param str parse: parse is the input(tree format)
and it is writen in as file
:return: stanford dependency universal format
:rtype: str
"""
# print("\nrunning.........")
package_directory = os.path.dirname(self.dep_par_path)
cwd = os.getcwd()
os.chdir(package_directory)
with open(self.senna_path + os.path.sep + "in.parse",
"w", encoding='utf-8') as parsefile:
parsefile.write(parse)
pipe = subprocess.Popen(self.default_jar_cli,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
pipe.wait()
stanford_out = pipe.stdout.read()
# print(stanford_out, "\n", self.default_jar_cli)
os.chdir(cwd)
return stanford_out.decode("utf-8").strip()
def get_batch_annotations(self, sentences, dep_parse=True):
"""
:param list sentences: list of sentences
:rtype: dict
"""
annotations = []
batch_senna_tags = self.get_senna_tag_batch(sentences)
for senna_tags in batch_senna_tags:
annotations += [self.get_annoations(senna_tags=senna_tags)]
if dep_parse:
syntax_tree = ""
for annotation in annotations:
syntax_tree += annotation['syntax_tree']
dependencies = self.get_dependency(syntax_tree).split("\n\n")
# print (dependencies)
if len(annotations) == len(dependencies):
for dependencie, annotation in zip(dependencies, annotations):
annotation["dep_parse"] = dependencie
return annotations
def get_annoations(self, sentence='', senna_tags=None, dep_parse=True):
"""
passing the string to senna and performing aboue given nlp process
and the returning them in a form of `dict()`
:param str or list sentence: a sentence or list of
sentence for nlp process.
:param str or list senna_tags: this values are by
SENNA processed string
:param bool batch: the change the mode into batch
processing process
:param bool dep_parse: to tell the code and user need
to communicate with stanford parser
:return: the dict() of every out in the process
such as ner, dep_parse, srl, verbs etc.
:rtype: dict
"""
annotations = {}
if not senna_tags:
senna_tags = self.get_senna_tag(sentence).decode()
senna_tags = [x.strip() for x in senna_tags.split("\n")]
senna_tags = senna_tags[0:-2]
else:
senna_tags = [x.strip() for x in senna_tags.split("\n")]
no_verbs = len(senna_tags[0].split("\t")) - 6
words = []
pos = []
chunk = []
ner = []
verb = []
srls = []
syn = []
for senna_tag in senna_tags:
senna_tag = senna_tag.split("\t")
words += [senna_tag[0].strip()]
pos += [senna_tag[1].strip()]
chunk += [senna_tag[2].strip()]
ner += [senna_tag[3].strip()]
verb += [senna_tag[4].strip()]
srl = []
for i in range(5, 5 + no_verbs):
srl += [senna_tag[i].strip()]
srls += [tuple(srl)]
syn += [senna_tag[-1]]
roles = []
for j in range(no_verbs):
role = {}
i = 0
temp = ""
curr_labels = [x[j] for x in srls]
for curr_label in curr_labels:
splits = curr_label.split("-")
if splits[0] == "S":
if len(splits) == 2:
if splits[1] == "V":
role[splits[1]] = words[i]
else:
if splits[1] in role:
role[splits[1]] += " " + words[i]
else:
role[splits[1]] = words[i]
elif len(splits) == 3:
if splits[1] + "-" + splits[2] in role:
role[splits[1] + "-" + splits[2]] += " " + words[i]
else:
role[splits[1] + "-" + splits[2]] = words[i]
elif splits[0] == "B":
temp = temp + " " + words[i]
elif splits[0] == "I":
temp = temp + " " + words[i]
elif splits[0] == "E":
temp = temp + " " + words[i]
if len(splits) == 2:
if splits[1] == "V":
role[splits[1]] = temp.strip()
else:
if splits[1] in role:
role[splits[1]] += " " + temp
role[splits[1]] = role[splits[1]].strip()
else:
role[splits[1]] = temp.strip()
elif len(splits) == 3:
if splits[1] + "-" + splits[2] in role:
role[splits[1] + "-" + splits[2]] += " " + temp
role[splits[1] + "-" + splits[2]] = role[splits[1] + "-" + splits[2]].strip()
else:
role[splits[1] + "-" + splits[2]] = temp.strip()
temp = ""
i += 1
if "V" in role:
roles += [role]
annotations['words'] = words
annotations['pos'] = list(zip(words, pos))
annotations['ner'] = list(zip(words, ner))
annotations['srl'] = roles
annotations['verbs'] = [x for x in verb if x != "-"]
annotations['chunk'] = list(zip(words, chunk))
annotations['dep_parse'] = ""
annotations['syntax_tree'] = ""
for (word_, syn_, pos_) in zip(words, syn, pos):
annotations['syntax_tree'] += syn_.replace("*", "(" + pos_ + " " + word_ + ")")
#annotations['syntax_tree']=annotations['syntax_tree'].replace("S1","S")
if dep_parse:
annotations['dep_parse'] = self.get_dependency(annotations
['syntax_tree'])
return annotations
def test(senna_path='', sent='',
dep_model='',
batch=False,
stp_dir=''):
"""please replace the path of yours environment(according to OS path)
.. warning::
deprecated:: 0.2.0.
See CLI doc instead. This `test()` function will be removed from next release.
:param str senna_path: path for senna location \n
:param str dep_model: stanford dependency parser model location \n
:param str or list sent: the sentence to process with Senna \n
:param bool batch: processing more than one sentence
in one row \n
:param str stp_dir: location of stanford-parser.jar file
"""
from pntl.utils import skipgrams
annotator = Annotator(senna_path, stp_dir, dep_model)
if not sent and batch:
sent = ["He killed the man with a knife and murdered"
"him with a dagger.",
"He is a good boy.",
"He created the robot and broke it after making it."]
elif not sent:
sent = 'get me a hotel on chennai in 21-4-2017 '
# "He created the robot and broke it after making it.
if not batch:
print("\n", sent, "\n")
sent = sent.split()
args = '-srl -pos'.strip().split()
print("conll:\n", annotator.get_conll_format(sent, args))
temp = annotator.get_annoations(sent, dep_parse=True)['dep_parse']
print('dep_parse:\n', temp)
temp = annotator.get_annoations(sent, dep_parse=True)['chunk']
print('chunk:\n', temp)
temp = annotator.get_annoations(sent, dep_parse=True)['pos']
print('pos:\n', temp)
temp = annotator.get_annoations(sent, dep_parse=True)['ner']
print('ner:\n', temp)
temp = annotator.get_annoations(sent, dep_parse=True)['srl']
print('srl:\n', temp)
temp = annotator.get_annoations(sent,
dep_parse=True)['syntax_tree']
print('syntaxTree:\n', temp)
temp = annotator.get_annoations(sent, dep_parse=True)['words']
print('words:\n', temp)
print('skip gram\n', list(skipgrams(sent, n=3, k=2)))
else:
print("\n\nrunning batch process", "\n", "=" * 20,
"\n", sent, "\n")
args = '-srl -pos'.strip().split()
print("conll:\n", annotator.get_conll_format(sent, args))
print(BLUE + "CoNLL format is recommented for batch process")
def findDependencyWord( strParam, orderNo ):
if orderNo == 0:
prm = re.compile('\((.*?)-', re.DOTALL | re.IGNORECASE).findall(strParam)
elif orderNo == 1:
prm = re.compile(', (.*?)-', re.DOTALL | re.IGNORECASE).findall(strParam)
if prm :
return prm[0]
def keyCheck(key, arr, default):
if key in arr.keys():
return arr[key]
else:
return default
def checkForAppropriateObjOrSub(srls,j,sType):
if (sType == 0):
for i in range(0,5):
if (keyCheck('ARG' + str(i), srls[j], "") != ''):
return srls[j]['ARG' + str(i)]
elif (sType == 1):
foundIndex = 0
for i in range(0,5):
if (keyCheck('ARG' + str(i), srls[j], "") != ''):
foundIndex = foundIndex + 1
if (foundIndex == 2):
return srls[j]['ARG' + str(i)]
elif (sType == 2):
foundIndex = 0
for i in range(0,6):
if (keyCheck('ARG' + str(i), srls[j], "") != ''):
foundIndex = foundIndex + 1
if (foundIndex == 3):
return srls[j]['ARG' + str(i)]
return ''
def getBaseFormOfVerb (verb):
#return lemma(verb)
#todo: pattern no longer working use another library!
with open('verbForms.txt', 'r') as myfile:
verb = verb.lower()
f=myfile.read()
oldString = find_between(f, "", "| "+verb+" ")
oldString = oldString + '|'
k = oldString.rfind("<")
newString = oldString[:k] + "_" + oldString[k+1:]
if find_between(newString, "_ ", " |") == '':
if find_between(f, "< "+verb+" "," >") == '':
with open('logs.txt', "a") as logFile:
logFile.write('Warning! Base form of verb '+verb+ ' not found\n')
print ('Warning! Base form of verb '+verb+ ' not found')
return verb
return find_between(newString, "_ ", " |")
def find_between( s, first, last ):
try:
start = s.index( first ) + len( first )
end = s.index( last, start )
return s[start:end]
except ValueError:
return ""
def getObjectPronun(text):
with open('objectPronouns.txt', 'r') as myfile:
f=myfile.read()
string = find_between(f, '< '+text.lower()+' | ', ' >')
if(string != ''): return string
return text
contractions_dict = {
"ain't": "am not; are not; is not; has not; have not",
"aren't": "are not",
"can't": "can not",
"can't've": "can not have",
"'cause": "because",
"could've": "could have",
"couldn't": "could not",
"couldn't've": "could not have",
"didn't": "did not",
"doesn't": "does not",
"don't": "do not",
"hadn't": "had not",
"hadn't've": "had not have",
"hasn't": "has not",
"haven't": "have not",
"he'd": "he had / he would",
"he'd've": "he would have",
"he'll": "he shall / he will",
"he'll've": "he shall have / he will have",
"he's": "he has / he is",
"how'd": "how did",
"how'd'y": "how do you",
"how'll": "how will",
"how's": "how has / how is / how does",
"I'd": "I had / I would",
"I'd've": "I would have",
"I'll": "I shall / I will",
"I'll've": "I shall have / I will have",
"I'm": "I am",
"I've": "I have",
"isn't": "is not",
"it'd": "it had / it would",
"it'd've": "it would have",
"it'll": "it shall / it will",
"it'll've": "it shall have / it will have",
"it's": "it has / it is",
"let's": "let us",
"ma'am": "madam",
"mayn't": "may not",
"might've": "might have",
"mightn't": "might not",
"mightn't've": "might not have",
"must've": "must have",
"mustn't": "must not",
"mustn't've": "must not have",
"needn't": "need not",
"needn't've": "need not have",
"o'clock": "of the clock",
"oughtn't": "ought not",
"oughtn't've": "ought not have",
"shan't": "shall not",
"sha'n't": "shall not",
"shan't've": "shall not have",
"she'd": "she had / she would",
"she'd've": "she would have",
"she'll": "she shall / she will",
"she'll've": "she shall have / she will have",
"she's": "she has / she is",
"should've": "should have",
"shouldn't": "should not",
"shouldn't've": "should not have",
"so've": "so have",
"so's": "so as / so is",
"that'd": "that would / that had",
"that'd've": "that would have",
"that's": "that has / that is",
"there'd": "there had / there would",
"there'd've": "there would have",
"there's": "there has / there is",
"they'd": "they had / they would",
"they'd've": "they would have",
"they'll": "they shall / they will",
"they'll've": "they shall have / they will have",
"they're": "they are",
"they've": "they have",
"to've": "to have",
"wasn't": "was not",
"we'd": "we had / we would",
"we'd've": "we would have",
"we'll": "we will",
"we'll've": "we will have",
"we're": "we are",
"we've": "we have",
"weren't": "were not",
"what'll": "what shall / what will",
"what'll've": "what shall have / what will have",
"what're": "what are",
"what's": "what has / what is",
"what've": "what have",
"when's": "when has / when is",
"when've": "when have",
"where'd": "where did",
"where's": "where has / where is",
"where've": "where have",
"who'll": "who shall / who will",
"who'll've": "who shall have / who will have",
"who's": "who has / who is",
"who've": "who have",
"why's": "why has / why is",
"why've": "why have",
"will've": "will have",
"won't": "will not",
"won't've": "will not have",
"would've": "would have",
"wouldn't": "would not",
"wouldn't've": "would not have",
"y'all": "you all",
"y'all'd": "you all would",
"y'all'd've": "you all would have",
"y'all're": "you all are",
"y'all've": "you all have",
"you'd": "you had / you would",
"you'd've": "you would have",
"you'll": "you shall / you will",
"you'll've": "you shall have / you will have",
"you're": "you are",
"you've": "you have"
}
contractions_re = re.compile('(%s)' % '|'.join(contractions_dict.keys()))
def expand_contractions(s, contractions_dict=contractions_dict):
def replace(match):
return contractions_dict[match.group(0)]
return contractions_re.sub(replace, s)
def generate(text):
text = re.sub(r'\([^)]*\)', '', text)
text = ' '.join(text.split())
text = text.replace(' ,', ',')
p = re.compile(r'(?:(?<!\w)\'((?:.|\n)+?\'?)(?:(?<!s)\'(?!\w)|(?<=s)\'(?!([^\']|\w\'\w)+\'(?!\w))))')
subst = "\"\g<1>\""
text = re.sub(p, subst, text)
"""
p1 = re.compile(r'(?:(?<!\w)\'((?:.|\n)+?\'?)(?:(?<!s)\'(?!\w)|(?<=s)\'(?!([^\']|\w\'\w)+\'(?!\w))))')
test_str = "'The Joneses' car'. Similar to the 'Kumbh melas', celebrated by the banks of the holy rivers of India. 'Hey'! you'll, I'm, he's, \nsome random text 'what if it's\nmultiline?'. 'I'm one of the persons''\n\n'the classes' hours'\n\n'the Joneses' car' guys' night out\n'two actresses' \nroles' and 'the hours' of classes'\n\n'The Joneses' car won't start'"
subst1 = "\"\g<1>\""
result = re.sub(p1, subst1, test_str)
print(result)
"""
predicates = []
subjects = []
objects = []
extraFields = []
types = []
#print annotator.getAnnotations("Similarly, as elevation increases there is less overlying atmospheric mass, so that pressure decreases with increasing elevation.",dep_parse=True)
#text = "REM sleep is characterized by darting movement of closed eyes."
#text = "In 1996, the trust employed over 7,000 staff and managed another six sites in Leeds and the surrounding area."
#text = "Early in the twentieth century, Thorstein Veblen, an American institutional economist, analysed cultural influences on consumption."
#text = "Some of Britain's most dramatic scenery is to be found in the Scottish Highlands."
#text = "Brain waves during REM sleep appear similar to brain waves during wakefulness."
#text = "The entire eastern portion of the Aral sea has become a sand desert, complete with the deteriorating hulls of abandoned fishing vessels."
#text = "He says that you like to swim."
#text = "Being able to link computers into networks has enormously boosted their capabilities."
#text = "Monetary policy should be countercyclical to counterbalance the business cycles of economic downturns and upswings."
#text = "I cheated my girlfriend."
#text = 'She looks very beautiful.'
#text = 'I go to school twice a day.'
#text = "I do not like to read science fiction."
#text = "The 1828 campaign was unique because of the party organization that promoted Jackson."
#text = "In a disputed 1985 ruling , the Commerce Commission said Commonwealth Edison could raise its electricity rates by $ 49 million to pay for the plant."
#text = "The strength of the depletion zone electric field increases as the reverse-bias voltage increases."
#text = "The first CCTV system was installed by Siemens AG at Test Stand VII in PeenemA_nde, Germany in 1942, for observing the launch of V-2 rockets."
text = expand_contractions(text)
print ("\n")
print ("Preprocessed text: "+ text)
textList = []
textList.append(text)
annotator = Annotator("./practnlptools", "./", "edu.stanford.nlp.trees.")
#annotations = annotator.get_batch_annotations(textList, dep_parse=True)[0]
try:
posTags = annotator.get_annoations(textList, dep_parse=False)['pos']
chunks = annotator.get_annoations(textList, dep_parse=False)['chunk']
except IndexError:
emptyList = []
return emptyList
#print ("chunks "+str(chunks))
predictor = Predictor.from_path("https://s3-us-west-2.amazonaws.com/allennlp/models/srl-model-2018.05.25.tar.gz")
srlResult = predictor.predict_json({"sentence": text})
srls = []
try:
for i in range(0,len(srlResult['verbs'])):
myDict = {}
description = srlResult['verbs'][i]['description']
while (find_between(description,"[","]") != ""):
parts = find_between(description,"[","]").split(": ")
myDict[parts[0]] = parts[1]
description = description.replace("["+find_between(description,"[","]")+"]", "")
if (find_between(description,"[","]") == ""):
srls.append(myDict)
except IndexError:
emptyList = []
return emptyList
#print("srls: "+str(srls))
nlp = spacy.load('en')
from spacy.symbols import nsubj
doc = nlp(u''+text)
for word in doc:
print(word.text, word.pos_, word.dep_, word.head.text)
for ent in doc.ents:
print(ent.label_, ent.text)
dativeWord = []
dativeVerb = []
dativeSubType = []
dobjWord = []
dobjVerb = []
dobjSubType = []
acompWord = []
acompVerb = []
acompSubType = []
attrWord = []
attrVerb = []
attrSubType = []
pcompPreposition = []
pcompWord = []
pcompSubType = []
dateWord = []
dateSubType = []
numWord = []
numSubType = []
personWord = []
personSubType = []
whereWord = []
whereSubType = []
foundQuestions = []
idiomJson = json.loads(open('idiom.json').read())
for word in doc:
if word.dep_ == 'dobj' or word.dep_ == 'ccomp' or word.dep_ == 'xcomp' or word.dep_ == 'dative' or word.dep_ == 'acomp' or word.dep_ == 'attr' or word.dep_ == "oprd":
try:
baseFormVerb = getBaseFormOfVerb(word.head.text)
if word.text.find(idiomJson[baseFormVerb]) != -1: continue
except KeyError:
pass
#what question / who question
if word.dep_ == 'dobj' or word.dep_ == 'ccomp' or word.dep_ == 'xcomp':
dobjVerb.append(word.head.text)
dobjWord.append(word.text)
dobjSubType.append('dobj')
if word.dep_ == 'dative':
dativeVerb.append(word.head.text)
dativeWord.append(word.text)
dativeSubType.append('dative')
if word.dep_ == 'acomp':
acompVerb.append(word.head.text)
acompWord.append(word.text)
acompSubType.append(word.dep_)
if word.dep_ == 'attr' or word.dep_ == "oprd":
attrVerb.append(word.head.text)
attrWord.append(word.text)
attrSubType.append('attr')
#what question
if word.dep_ == 'pcomp':
pcompPreposition.append(word.head.text)
pcompWord.append(word.text)
pcompSubType.append(word.dep_)
for ent in doc.ents:
#when question
if (ent.label_ == 'DATE' and ent.text.find('year old') == -1 and ent.text.find('years old') == -1 ):
dateWord.append(ent.text)
dateSubType.append(ent.label_)
#how many question
if ent.label_ == 'CARDINAL':
numWord.append(ent.text)
numSubType.append(ent.label_)
#who question
if ent.label_ == 'PERSON':
personWord.append(ent.text)
personSubType.append(ent.label_)
#where question
if ent.label_ == 'FACILITY' or ent.label_ == 'ORG' or ent.label_ == 'GPE' or ent.label_ == 'LOC':
whereWord.append(ent.text)
whereSubType.append('LOC')
#Beginning of deconstruction stage
for i in range(0,len(dativeWord)):
for k in range(0,len(dobjWord)):
if dobjVerb[k] != dativeVerb[i]: continue
for j in range(0,len(srls)):
foundSubject = checkForAppropriateObjOrSub(srls,j,0)
foundObject = checkForAppropriateObjOrSub(srls,j,1)
foundIndirectObject = checkForAppropriateObjOrSub(srls,j,2)
if (foundSubject == '') or (foundObject == '') or (foundSubject == foundObject) or (keyCheck('V', srls[j], "") == ""): continue
if (foundIndirectObject == '') or (foundIndirectObject == foundObject) or (foundIndirectObject == foundSubject): continue
elif (srls[j]['V'] == dobjVerb[k]) and (foundObject.find(dobjWord[k]) != -1 ) and (foundIndirectObject.find(dativeWord[i]) != -1 ):
index =1 -1
totalPredicates = srls[j]['V']
for k in range(0,len(chunks)):
found = re.compile(srls[j]['V'], re.DOTALL | re.IGNORECASE).findall(str(chunks[k]))
if found:
index = k
for k in range(0,index):
reversedIndex = index -1 -k
if reversedIndex == -1: break
resultType = re.search("', '(.*)'\)", str(chunks[reversedIndex]))
try:
if resultType.group(1) == 'B-VP' or resultType.group(1) == 'E-VP' or resultType.group(1) == 'I-VP' or resultType.group(1) == 'S-VP':
result = re.search("\('(.*)',", str(chunks[reversedIndex]))
if foundSubject.find(result.group(1)) != -1: break
totalPredicates = result.group(1) + ' ' + totalPredicates
else: break
except AttributeError:
break
nextIndex = index + 1
if (srls[j]['V'] != 'am' and srls[j]['V'] != 'is' and srls[j]['V'] != 'are' and srls[j]['V'] != 'was' and srls[j]['V'] != 'were' and srls[j]['V'] != 'be'):
if (nextIndex < len(chunks)):
resultType = re.search("', '(.*)'\)", str(chunks[nextIndex]))
try:
if resultType.group(1) == 'S-PRT':
result = re.search("\('(.*)',", str(chunks[nextIndex]))
if foundSubject.find(result.group(1)) != -1: break
totalPredicates = result.group(1) + ' ' + totalPredicates
except AttributeError:
pass
if totalPredicates[:3] == 'to ':
totalPredicates= totalPredicates[3:]
predicates.append(totalPredicates)
objects.append(foundIndirectObject + " " + foundObject)
subjects.append(foundSubject)
extraFieldsString = ''
if keyCheck('ARGM-LOC',srls[j],'') != '' and (totalPredicates.find(keyCheck('ARGM-LOC',srls[j],'')) == -1):
extraFieldsString = keyCheck('ARGM-LOC',srls[j],'')
if keyCheck('ARGM-TMP',srls[j],'') != '' and (totalPredicates.find(keyCheck('ARGM-TMP',srls[j],'')) == -1):
extraFieldsString = extraFieldsString + ' ' + keyCheck('ARGM-TMP',srls[j],'')
extraFields.append(extraFieldsString)
types.append(dativeSubType[i])
for i in range(0,len(dobjWord)):
for j in range(0,len(srls)):
foundSubject = checkForAppropriateObjOrSub(srls,j,0)
foundObject = checkForAppropriateObjOrSub(srls,j,1)
if (foundSubject == '') or (foundObject == '') or (foundSubject == foundObject) or (keyCheck('V', srls[j], "") == ""): continue
elif (srls[j]['V'] == dobjVerb[i]) and (foundObject.find(dobjWord[i]) != -1 ) :
index =1 -1
totalPredicates = srls[j]['V']
for k in range(0,len(chunks)):
found = re.compile(srls[j]['V'], re.DOTALL | re.IGNORECASE).findall(str(chunks[k]))
if found:
index = k
for k in range(0,index):
reversedIndex = index -1 -k
if reversedIndex == -1: break
resultType = re.search("', '(.*)'\)", str(chunks[reversedIndex]))
try:
if resultType.group(1) == 'B-VP' or resultType.group(1) == 'E-VP' or resultType.group(1) == 'I-VP' or resultType.group(1) == 'S-VP':
result = re.search("\('(.*)',", str(chunks[reversedIndex]))
if foundSubject.find(result.group(1)) != -1: break
totalPredicates = result.group(1) + ' ' + totalPredicates
else: break
except AttributeError:
break
nextIndex = index + 1
if (srls[j]['V'] != 'am' and srls[j]['V'] != 'is' and srls[j]['V'] != 'are' and srls[j]['V'] != 'was' and srls[j]['V'] != 'were' and srls[j]['V'] != 'be'):
if (nextIndex < len(chunks)):
resultType = re.search("', '(.*)'\)", str(chunks[nextIndex]))
try:
if resultType.group(1) == 'S-PRT':
result = re.search("\('(.*)',", str(chunks[nextIndex]))
if foundSubject.find(result.group(1)) != -1: break
totalPredicates = result.group(1) + ' ' + totalPredicates
except AttributeError:
pass