-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPETRreader.py
More file actions
executable file
·2314 lines (1940 loc) · 85.1 KB
/
Copy pathPETRreader.py
File metadata and controls
executable file
·2314 lines (1940 loc) · 85.1 KB
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
## PETRreader.py [module]
##
# Dictionary and text input routines for the PETRARCH event coder
##
# CODE REPOSITORY: https://github.com/eventdata/PETRARCH
##
# SYSTEM REQUIREMENTS
# This program has been successfully run under Mac OS 10.10; it is standard Python 2.7
# so it should also run in Unix or Windows.
#
# INITIAL PROVENANCE:
# Programmer: Philip A. Schrodt
# Parus Analytics
# Charlottesville, VA, 22901 U.S.A.
# http://eventdata.parusanalytics.com
#
#
# Clayton Norris
# Caerus Associates/ University of Chicago
#
# GitHub repository: https://github.com/openeventdata/petrarch
#
# Copyright (c) 2014 Philip A. Schrodt. All rights reserved.
#
# This project is part of the Open Event Data Alliance tool set; earlier developments
# were funded in part by National Science Foundation grant SES-1259190
#
# This code is covered under the MIT license
#
# Report bugs to: schrodt735@gmail.com
#
# REVISION HISTORY:
# 22-Nov-13: Initial version
# Summer-14: Numerous modifications to handle synonyms in actor and verb dictionaries
# 20-Nov-14: write_actor_root/text added to parse_Config
# ------------------------------------------------------------------------
from __future__ import print_function
from __future__ import unicode_literals
import io
import re
import os
import sys
import math # required for ordinal date calculations
import logging
import xml.etree.ElementTree as ET
from datetime import datetime
try:
from ConfigParser import ConfigParser
except ImportError:
from configparser import ConfigParser
import PETRglobals
import utilities
# ================== STRINGS ================== #
ErrMsgMissingDate = "<Sentence> missing required date; record was skipped"
# ================== EXCEPTIONS ================== #
class DateError(Exception): # invalid date
pass
# ================== CONFIG FILE INPUT ================== #
def parse_Config(config_path):
"""
Parse PETRglobals.ConfigFileName. The file should be ; the default is PETR_config.ini
in the working directory but this can be changed using the -c option in the command
line. Most of the entries are obvious (but will eventually be documented) with the
exception of
1. actorfile_list and textfile_list are comma-delimited lists. Per the usual rules
for Python config files, these can be continued on the next line provided the
the first char is a space or tab.
2. If both textfile_list and textfile_name are present, textfile_list takes priority.
textfile_list should be the name of a file containing text file names; # is allowed
as a comment delimiter at the beginning of individual lines and following the file
name.
3. For additional info on config files, see
http://docs.python.org/3.4/library/configparser.html
or try Google, but basically, it is fairly simple, and you can probably just
follow the examples.
"""
def get_config_boolean(optname):
""" Checks for the option optname, prints outcome and returns the result.
If optname not present, returns False """
if parser.has_option('Options', optname):
try:
result = parser.getboolean('Options', optname)
print(optname, "=", result)
return result
except ValueError:
print(
"Error in config.ini: " +
optname +
" value must be `true' or `false'")
raise
else:
return False
print('\n', end=' ')
parser = ConfigParser()
# logger.info('Found a config file in working directory')
# print "pc",PETRglobals.ConfigFileName
confdat = parser.read(config_path)
if len(confdat) == 0:
print(
"\aError: Could not find the config file:",
PETRglobals.ConfigFileName)
print("Terminating program")
sys.exit()
try:
PETRglobals.VerbFileName = parser.get('Dictionaries', 'verbfile_name')
PETRglobals.AgentFileName = parser.get(
'Dictionaries',
'agentfile_name')
# print "pc",PETRglobals.AgentFileName
PETRglobals.DiscardFileName = parser.get(
'Dictionaries',
'discardfile_name')
direct = parser.get('StanfordNLP', 'stanford_dir')
PETRglobals.stanfordnlp = os.path.expanduser(direct)
filestring = parser.get('Dictionaries', 'actorfile_list')
PETRglobals.ActorFileList = filestring.split(', ')
# otherwise this was set in command line
if len(PETRglobals.TextFileList) == 0:
if parser.has_option('Options', 'textfile_list'): # takes priority
filestring = parser.get('Options', 'textfile_list')
PETRglobals.TextFileList = filestring.split(', ')
else:
filename = parser.get('Options', 'textfile_name')
try:
fpar = open(filename, 'r')
except IOError:
print(
"\aError: Could not find the text file list file:",
filename)
print("Terminating program")
sys.exit()
PETRglobals.TextFileList = []
line = fpar.readline()
while len(line) > 0: # go through the entire file
if '#' in line:
line = line[:line.find('#')]
line = line.strip()
if len(line) > 0:
PETRglobals.TextFileList.append(line)
line = fpar.readline()
fpar.close()
if parser.has_option('Dictionaries', 'issuefile_name'):
PETRglobals.IssueFileName = parser.get(
'Dictionaries',
'issuefile_name')
if parser.has_option('Options', 'new_actor_length'):
try:
PETRglobals.NewActorLength = parser.getint(
'Options',
'new_actor_length')
except ValueError:
print(
"Error in config.ini Option: new_actor_length value must be an integer")
raise
print("new_actor_length =", PETRglobals.NewActorLength)
PETRglobals.StoponError = get_config_boolean('stop_on_error')
PETRglobals.WriteActorRoot = get_config_boolean('write_actor_root')
PETRglobals.WriteActorText = get_config_boolean('write_actor_text')
PETRglobals.WriteEventText = get_config_boolean('write_event_text')
if parser.has_option(
'Options', 'require_dyad'): # this one defaults to True
PETRglobals.RequireDyad = get_config_boolean('require_dyad')
else:
PETRglobals.RequireDyad = True
# otherwise this was set in command line
if len(PETRglobals.EventFileName) == 0:
PETRglobals.EventFileName = parser.get('Options', 'eventfile_name')
PETRglobals.CodeBySentence = parser.has_option(
'Options',
'code_by_sentence')
print("code-by-sentence", PETRglobals.CodeBySentence)
PETRglobals.PauseBySentence = parser.has_option(
'Options',
'pause_by_sentence')
print("pause_by_sentence", PETRglobals.PauseBySentence)
PETRglobals.PauseByStory = parser.has_option(
'Options',
'pause_by_story')
print("pause_by_story", PETRglobals.PauseByStory)
try:
if parser.has_option('Options', 'comma_min'):
PETRglobals.CommaMin = parser.getint('Options', 'comma_min')
elif parser.has_option('Options', 'comma_max'):
PETRglobals.CommaMax = parser.getint('Options', 'comma_max')
elif parser.has_option('Options', 'comma_bmin'):
PETRglobals.CommaBMin = parser.getint('Options', 'comma_bmin')
elif parser.has_option('Options', 'comma_bmax'):
PETRglobals.CommaBMax = parser.getint('Options', 'comma_bmax')
elif parser.has_option('Options', 'comma_emin'):
PETRglobals.CommaEMin = parser.getint('Options', 'comma_emin')
elif parser.has_option('Options', 'comma_emax'):
PETRglobals.CommaEMax = parser.getint('Options', 'comma_emax')
except ValueError:
print(
"Error in config.ini Option: comma_* value must be an integer")
raise
print("Comma-delimited clause elimination:")
print("Initial :", end=' ')
if PETRglobals.CommaBMax == 0:
print("deactivated")
else:
print(
"min =",
PETRglobals.CommaBMin,
" max =",
PETRglobals.CommaBMax)
print("Internal:", end=' ')
if PETRglobals.CommaMax == 0:
print("deactivated")
else:
print(
"min =",
PETRglobals.CommaMin,
" max =",
PETRglobals.CommaMax)
print("Terminal:", end=' ')
if PETRglobals.CommaEMax == 0:
print("deactivated")
else:
print(
"min =",
PETRglobals.CommaEMin,
" max =",
PETRglobals.CommaEMax)
except Exception as e:
print(
'parse_config() encountered an error: check the options in',
PETRglobals.ConfigFileName)
print("Terminating program")
sys.exit()
# logger.warning('Problem parsing config file. {}'.format(e))
# ================== PRIMARY INPUT USING FIN ================== #
def open_FIN(filename, descrstr):
# opens the global input stream fin using filename;
# descrstr provides information about the file in the event it isn't found
global FIN
global FINline, FINnline, CurrentFINname
try:
FIN = io.open(filename, 'r', encoding='utf-8')
CurrentFINname = filename
FINnline = 0
except IOError:
print("\aError: Could not find the", descrstr, "file:", filename)
print("Terminating program")
sys.exit()
def close_FIN():
# closes the global input stream fin.
# IOError should only happen during debugging or if something has seriously gone wrong
# with the system, so exit if this occurs.
global FIN
try:
FIN.close()
except IOError:
print("\aError: Could not close the input file")
print("Terminating program")
sys.exit()
def read_FIN_line():
"""
def read_FIN_line():
Reads a line from the input stream fin, deleting xml comments and lines beginning with #
returns next non-empty line or EOF
tracks the current line number (FINnline) and content (FINline)
calling function needs to handle EOF (len(line) == 0)
"""
"""
Comments in input files:
Comments should be delineated in the XML style (which is inherited from HTML which
inherited it from SGML) are allowed, as long as you don't get too clever. Basically,
anything that looks like any of these
<!-- [comment] -->
things I want to actually read <!-- [comment] -->
some things I want <!-- [comment] --> and more of them
<!-- start of the comment
[1 or more additional lines
end of the comment -->
is treated like a comment and skipped.
Note: the system doesn't use the formal definition that also says '--' is not allowed
inside a comment: it just looks for --> as a terminator
The system is *not* set up to handle clever variations like nested comments, multiple
comments on a line, or non-comment information in multi-line comments: yes, we are
perfectly capable of writing code that could handle these contingencies, but it
is not a priority at the moment. We trust you can cope within these limits.
For legacy purposes, the perl/Python one-line comment delimiter # the beginning of a
line is also recognized.
To accommodate my habits, the perl/Python one-line comment delimiter ' #' is also
recognized at the end of a line and material following it is eliminated. Note that the
initial space is required.
Blank lines and lines with only whitespace are also skipped.
"""
global FIN
global FINline, FINnline
line = FIN.readline()
FINnline += 1
while True:
# print '==',line,
if len(line) == 0:
break # calling function needs to handle EOF
# deal with simple lines we need to skip
if line[0] == '#' or line[0] == '\n' or line[
0:2] == '<!' or len(line.strip()) == 0:
line = FIN.readline()
FINnline += 1
continue
if not line: # handle EOF
print("EOF hit in read_FIN_line()")
raise EOFError
return line
if ('#' in line):
line = line[:line.find('#')]
if ('<!--' in line):
if ('-->' in line): # just remove the substring
pline = line.partition('<!--')
line = pline[0] + pline[2][pline[2].find('-->') + 3:]
else:
while ('-->' not in line):
line = FIN.readline()
FINnline += 1
line = FIN.readline()
FINnline += 1
if len(line.strip()) > 0:
break
line = FIN.readline()
FINnline += 1
# print "++",line
FINline = line
return line
# ========================== TAG EVALUATION FUNCTIONS ========================== #
def find_tag(tagstr):
# reads fin until tagstr is found
# can inherit EOFError raised in PETRreader.read_FIN_line()
line = read_FIN_line()
while (tagstr not in line):
line = read_FIN_line()
def extract_attributes(theline):
# puts list of attribute and content pairs in the global AttributeList. First item is
# the tag itself
# If a twice-double-quote occurs -- "" -- this treated as "\"
# still to do: need error checking here
"""
Structure of attributes extracted to AttributeList
At present, these always require a quoted field which follows an '=', though it
probably makes sense to make that optional and allow attributes without content
"""
# print "PTR-1:", theline,
theline = theline.strip()
if ' ' not in theline: # theline only contains a keyword
PETRglobals.AttributeList = theline[1:-2]
# print "PTR-1.1:", PETRglobals.AttributeList
return
pline = theline[1:].partition(' ') # skip '<'
PETRglobals.AttributeList = [pline[0]]
theline = pline[2]
while ('=' in theline): # get the field and content pairs
pline = theline.partition('=')
PETRglobals.AttributeList.append(pline[0].strip())
theline = pline[2]
pline = theline.partition('"')
if pline[2][0] == '"': # twice-double-quote
pline = pline[2][1:].partition('"')
PETRglobals.AttributeList.append('"' + pline[0] + '"')
theline = pline[2][1:]
else:
pline = pline[2].partition('"')
PETRglobals.AttributeList.append(pline[0].strip())
theline = pline[2]
# print "PTR-2:", PETRglobals.AttributeList
def check_attribute(targattr):
""" Looks for targetattr in AttributeList; returns value if found, null string otherwise."""
# This is used if the attribute is optional (or if error checking is handled by the calling
# routine); if an error needs to be raised, use get_attribute()
if (targattr in PETRglobals.AttributeList):
return (
PETRglobals.AttributeList[
PETRglobals.AttributeList.index(targattr) + 1]
)
else:
return ""
def get_attribute(targattr):
""" Similar to check_attribute() except it raises a MissingAttr error when the attribute is missing."""
if (targattr in PETRglobals.AttributeList):
return (
PETRglobals.AttributeList[
PETRglobals.AttributeList.index(targattr) + 1]
)
else:
#raise MissingAttr #commented by me
return ""
# ================== ANCILLARY DICTIONARY INPUT ================== #
def read_discard_list(discard_path):
"""
Reads file containing the discard list: these are simply lines containing strings.
If the string, prefixed with ' ', is found in the <Text>...</Text> sentence, the
sentence is not coded. Prefixing the string with a '+' means the entire story is not
coded with the string is found [see read_record() for details on story/sentence
identification]. If the string ends with '_', the matched string must also end with
a blank or punctuation mark; otherwise it is treated as a stem. The matching is not
case sensitive.
The file format allows # to be used as a in-line comment delimiter.
File is stored as a simple list and the interpretation of the strings is done in
check_discards()
===== EXAMPLE =====
+5K RUN # ELH 06 Oct 2009
+ACADEMY AWARD # LRP 08 Mar 2004
AFL GRAND FINAL # MleH 06 Aug 2009
AFRICAN NATIONS CUP # ab 13 Jun 2005
AMATEUR BOXING TOURNAMENT # CTA 30 Jul 2009
AMELIA EARHART
ANDRE AGASSI # LRP 10 Mar 2004
ASIAN CUP # BNL 01 May 2003
ASIAN FOOTBALL # ATS 9/27/01
ASIAN MASTERS CUP # CTA 28 Jul 2009
+ASIAN WINTER GAMES # sls 14 Mar 2008
ATP HARDCOURT TOURNAMENT # mj 26 Apr 2006
ATTACK ON PEARL HARBOR # MleH 10 Aug 2009
AUSTRALIAN OPEN
AVATAR # CTA 14 Jul 2009
AZEROTH # CTA 14 Jul 2009 (World of Warcraft)
BADMINTON # MleH 28 Jul 2009
BALLCLUB # MleH 10 Aug 2009
BASEBALL
BASKETBALL
BATSMAN # MleH 14 Jul 2009
BATSMEN # MleH 12 Jul 2009
"""
logger = logging.getLogger('petr_log')
logger.info("Reading " + PETRglobals.DiscardFileName)
open_FIN(discard_path, "discard")
line = read_FIN_line()
while len(line) > 0: # loop through the file
if '#' in line:
line = line[:line.find('#')]
targ = line.strip()
if targ.startswith('+'):
targ = targ[1:].upper() + ' +'
else:
targ = targ.upper() + ' $'
targ = targ.split()
prev = targ[0] # Add words to search tree
targ = targ[1:]
list = PETRglobals.DiscardList.setdefault(prev, {})
while targ != []:
list = list.setdefault(targ[0], {})
targ = targ[1:]
line = read_FIN_line()
close_FIN()
def read_issue_list(issue_path):
"""
"Issues" do simple string matching and return a comma-delimited list of codes.
The standard format is simply
<string> [<code>]
For purposes of matching, a ' ' is added to the beginning and end of the string: at
present there are not wild cards, though that is easily added.
The following expansions can be used (these apply to the string that follows up to
the next blank)
n: Create the singular and plural of the noun
v: Create the regular verb forms ('S','ED','ING')
+: Create versions with ' ' and '-'
The file format allows # to be used as a in-line comment delimiter.
File is stored in PETRglobals.IssueList as a list of tuples (string, index) where
index refers to the location of the code in PETRglobals.IssueCodes. The coding is done
in check_issues()
Issues are written to the event record as a comma-delimited list to a tab-delimited
field, e.g.
20080801 ABC EDF 0001 POSTSECONDARY_EDUCATION 2, LITERACY 1 AFP0808-01-M008-02
20080801 ABC EDF 0004 AFP0808-01-M007-01
20080801 ABC EDF 0001 NUCLEAR_WEAPONS 1 AFP0808-01-M008-01
where XXXX NN, corresponds to the issue code and the number of matched phrases in the
sentence that generated the event.
This feature is optional and triggered by a file name in the PETR_config.ini file at
issuefile_name = Phoenix.issues.140225.txt
<14.02.28> NOT YET FULLY IMPLEMENTED
The prefixes '~' and '~~' indicate exclusion phrases:
~ : if the string is found in the current sentence, do not code any of the issues
in section -- delimited by <ISSUE CATEGORY="...">...</ISSUE> -- containing
the string
~~ : if the string is found in the current *story*, do not code any of the issues
in section
In the current code, the occurrence of an ignore phrase of either type cancels all
coding of issues from the sentence
===== EXAMPLE =====
<ISSUE CATEGORY="ID_ATROCITY">
n:atrocity [ID_ATROCITY]
n:genocide [ID_ATROCITY]
ethnic cleansing [ID_ATROCITY]
ethnic v:purge [ID_ATROCITY]
ethnic n:purge [ID_ATROCITY]
war n:crime [ID_ATROCITY]
n:crime against humanity [ID_ATROCITY]
n:massacre [ID_ATROCITY]
v:massacre [ID_ATROCITY]
al+zarqawi network [NAMED_TERROR_GROUP]
~Saturday Night massacre
~St. Valentine's Day massacre
~~Armenian genocide # not coding historical cases
</ISSUE>
"""
PETRglobals.IssueList = {}
logger = logging.getLogger('petr_log')
logger.info("Reading " + PETRglobals.IssueFileName)
open_FIN(issue_path, "issues")
PETRglobals.IssueCodes.append('~') # initialize the ignore codes
PETRglobals.IssueCodes.append('~~')
line = read_FIN_line()
while len(line) > 0: # loop through the file
if '#' in line:
line = line[:line.find('#')]
if line[0] == '~': # ignore codes are only partially implemented
if line[1] == '~':
target = line[2:].strip().upper()
codeindex = 1
else:
target = line[1:].strip().upper()
codeindex = 0
else:
if '[' not in line: # just do the codes now
line = read_FIN_line()
continue
code = line[line.find('[') + 1:line.find(']')] # get the code
if code in PETRglobals.IssueCodes:
codeindex = PETRglobals.IssueCodes.index(code)
else:
PETRglobals.IssueCodes.append(code)
codeindex = len(PETRglobals.IssueCodes) - 1
target = line[:line.find('[')].strip().upper()
forms = [target]
madechange = True
while madechange: # iterate until no more changes to make
ka = 0
madechange = False
while ka < len(forms):
if '+' in forms[ka]:
str = forms[ka]
forms[ka] = str.replace('+', ' ', 1)
forms.insert(ka + 1, str.replace('+', '-', 1))
madechange = True
if 'N:' in forms[ka]: # regular noun forms
part = forms[ka].partition('N:')
forms[ka] = part[0] + part[2]
plur = part[2].partition(' ')
if 'Y' == plur[0][-1]:
plural = plur[0][:-1] + 'IES'
else:
plural = plur[0] + 'S'
forms.insert(ka + 1, part[0] + plural + ' ' + plur[2])
madechange = True
if 'V:' in forms[ka]: # regular verb forms
part = forms[ka].partition('V:')
forms[ka] = part[0] + part[2]
root = part[2].partition(' ')
vscr = root[0] + "S"
forms.insert(ka + 1, part[0] + vscr + ' ' + root[2])
if root[0][-1] == 'E': # root ends in 'E'
vscr = root[0] + "D "
forms.insert(ka + 2, part[0] + vscr + ' ' + root[2])
vscr = root[0][:-1] + "ING "
else:
vscr = root[0] + "ED "
forms.insert(ka + 2, part[0] + vscr + ' ' + root[2])
vscr = root[0] + "ING "
forms.insert(ka + 3, part[0] + vscr + ' ' + root[2])
madechange = True
ka += 1
for item in forms:
segs = item.split()+['#']
path = PETRglobals.IssueList
while not segs == ['#']:
path = path.setdefault(segs[0],{})
segs = segs[1:]
path[segs[0]] = codeindex
line = read_FIN_line()
close_FIN()
""" debug
ka = 0
while ka < 128 :
print PETRglobals.IssueList[ka],PETRglobals.IssueCodes[PETRglobals.IssueList[ka][1]]
ka += 1
"""
# ================== VERB DICTIONARY INPUT ================== #
def make_plural_noun(noun):
""" Create the plural of a synonym noun st """
if noun[-1] == '_' or noun[0] == '{':
return None
if 'Y' == noun[-1]:
return noun[:-1] + 'IES'
elif 'S' == noun[-1]:
return noun[:-1] + 'ES'
else:
return noun + 'S'
def read_verb_dictionary(verb_path):
"""
Verb storage:
Storage sequence:
Upper Noun phrases
|
Upper prepositional phrases
*
Lower noun phrases
|
Lower prepositional phrases
#
- symbol acts as extender, indicating the noun phrase is longer
, symbol acts as delimiter between several selected options
"""
logger = logging.getLogger('petr_log')
logger.info("Reading " + PETRglobals.VerbFileName)
file = open(verb_path,'r')
block_meaning = ""
block_code = ""
record_patterns = 1
synsets = {}
syn =1
def resolve_synset(line):
segs = line.split()
#print(line)
syns = filter(lambda a: a.startswith('&'), segs)
lines = []
if syns:
set = syns[0].replace("{","").replace("}","").replace("(","").replace(")","")
if set in synsets:
for word in synsets[set]:
#print(word)
lines += resolve_synset(line.replace(set,word,1))
plural = make_plural_noun(word)
if plural :
lines+=resolve_synset(line.replace(set,plural,1))
return lines
else:
print("Undefined synset", set)
return [line]
def resolve_patseg(segment):
prepphrase = 0
nounphrase = 0
nps = []
head = ""
modifiers = []
index = 0
prepstarts=[]
prepends=[]
for element in segment:
# SKIP OVER PREPS, We consider these later
if element.endswith(")"):
prepends.append(index)
if element.startswith("("):
prepstarts.append(index)
prepphrase = 0
elif element.startswith("("):
prepstarts.append(index)
prepphrase = 1
elif not prepphrase:
# Find noun phrases
if element.endswith("}"):
nounphrase = 0
head = element[:-1]
nps.append((head,modifiers))
modifiers = []
elif nounphrase:
modifiers.append(element)
elif element.startswith("{"):
modifiers.append(element[1:])
nounphrase = 1
else:
nps.append(element)
index += 1
preps = map(lambda a: segment[a[0]:a[1]+1], zip(prepstarts,prepends))
prep_pats = []
for phrase in preps:
phrase = map(lambda a: a.replace("(","").replace(")",""), phrase)
p = phrase[0]
pnps = []
pmodifiers = []
if len(phrase)> 1:
head = ""
for element in phrase[1:]:
# Find noun phrases
if element.endswith("}"):
nounphrase = 0
head = element[:-1]
pnps.append((head,pmodifiers))
pmodifiers = []
elif nounphrase:
pmodifiers.append(element)
elif element.startswith("{"):
pmodifiers.append(element[1:])
nounphrase = 1
else:
pnps.append(element)
prep_pats.append((p,pnps))
return nps,prep_pats
for line in file:
if line.startswith("<!"):
record_patterns= 0
continue
elif line.startswith("####### VERB PATTERNS #######"):
syn = 0
if not line.strip():
continue
if line.startswith("---"):
segs = line.split()
block_meaning = segs[1]
block_code = segs[2]
elif line.startswith("-"):
if not record_patterns:
continue
dict_entry = {}
pattern = line[1:].split("#")[0]
#print(line)
for pat in resolve_synset(pattern):
segs = pat.split("*")
pre = segs[0].split()
pre = resolve_patseg(pre)
post = segs[1].split()
code = post.pop()
post = resolve_patseg(post)
path = PETRglobals.VerbDict['phrases'].setdefault(block_meaning,{})
if not pre == ([],[]):
if pre[0]:
count = 1
for noun in pre[0]:
if not isinstance(noun,tuple):
path = path.setdefault(noun,{})
else:
head = noun[0]
path = path.setdefault(head,{})
for element in noun[1]:
path = path.setdefault("-",{})
path = path.setdefault(element,{})
path = path.setdefault(",",{}) if not count == len(pre[0]) else path
count += 1
if pre[1]:
path = path.setdefault("|",{})
for phrase in pre[1]:
head = phrase[0]
path = path.setdefault(head,{})
count = 1
for noun in phrase[1]:
if not isinstance(noun,tuple):
path = path.setdefault("-",{})
path = path.setdefault(noun,{})
else:
head = noun[0]
path = path.setdefault(head,{})
for element in noun[1]:
path = path.setdefault("-",{})
path = path.setdefault(element,{})
path = path.setdefault(",",{}) if not count == len(phrase[1]) else path
count += 1
if not post == ([],[]):
path = path.setdefault('*',{})
if post[0]:
count = 1
for noun in post[0]:
if not isinstance(noun,tuple):
path = path.setdefault(noun,{})
else:
head = noun[0]
path = path.setdefault(head,{})
for element in noun[1]:
path = path.setdefault("-",{})
path = path.setdefault(element,{})
path = path.setdefault(",",{}) if not count == len(post[0]) else path
if post[1]:
for phrase in post[1]:
head = phrase[0]
path = path.setdefault("|",{})
path = path.setdefault(head,{})
count = 1
for noun in phrase[1]:
if not isinstance(noun,tuple):
path = path.setdefault("-",{})
path = path.setdefault(noun,{})
else:
head = noun[0]
path = path.setdefault("-",{})
path = path.setdefault(head,{})
for element in noun[1]:
path = path.setdefault("-",{})
path = path.setdefault(element,{})
path = path.setdefault(",",{}) if not count == len(phrase[1]) else path
count += 1
path["#"] = {'code' : code[1:-1], 'line' : line[:-1]}
elif syn and line.startswith("&"):
block_meaning = line.strip()
elif syn and line.startswith("+"):
term = line.strip()[1:]
if "_" in term:
if len(term.replace("_"," ").split()) > 1:
term = "{" + term.replace("_"," ") + "}"
else:
term = term.replace("_"," ")
synsets[block_meaning] = synsets.setdefault(block_meaning,[]) + [term]
elif line.startswith("~"):
# VERB TRANSFORMATION
p = line[1:].replace("(","").replace(")","")
segs = p.split("=")
pat = segs[0].split()
answer = segs[1].split()
ev2 = pat
path = PETRglobals.VerbDict['transformations']
while len(ev2) > 1:
source = ev2[0]
verb = reduce(lambda a,b : a + b ,
map(lambda c: utilities.convert_code(PETRglobals.VerbDict['verbs'][c]['#']['#']['code'])[0] if not c== "Q" else -1,
ev2[-1].split("_")), 0)
path = path.setdefault(verb,{})
path = path.setdefault(source,{})
ev2 = ev2[1:-1]
path[ev2[0]] = [answer,line]
else:
# Add synonyms
word = line.split("#")[0]
words = word.replace("}","").replace("{","").split()
if not words:
continue
code = block_code
front = []
back = []
compound = 0
stem = words[0]
if "_" in stem:
# We're dealing with a compound verb
# print(stem)
segs = stem.split('+')
front = segs[0].split('_')
back = segs[1].split('_')[1:]
stem = segs[1].split('_')[0]
compound = 1
if words[-1].startswith("["):
code = words.pop()
if not (len(words) > 1 or '{' in word):
if stem.endswith("S") or stem.endswith("X") or stem.endswith("Z"):
words.append(stem + "ES")
elif stem.endswith("Y"):
words.append(stem[:-1] + "IES")
else:
words.append(stem + "S")
if stem.endswith("E"):
words.append(stem + "D")
else:
words.append(stem+"ED")
if stem.endswith("E") and not stem[-2] in "AEIOU":
words.append(stem[:-1] + "ING")
else:
words.append(stem + "ING")
for w in words:
wstem = w
if "_" in w:
segs = w.split('+')
front = segs[0].split('_')