-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconll2xml.pm
2025 lines (1841 loc) · 71.4 KB
/
conll2xml.pm
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
#!/usr/bin/perl
use strict;
use utf8;
use XML::LibXML;
binmode STDIN, ':utf8';
binmode STDOUT, ':utf8';
binmode (STDERR);
use File::Spec::Functions qw(rel2abs);
use File::Basename;
my %mapCliticToEaglesTag = (
'la' => 'PP3FSA00',
'las' => 'PP3FPA00',
'lo' => 'PP3MSA00',
'los' => 'PP3MPA00',
'le' => 'PP3CSD00',
'les' => 'PP3CPD00',
'me' => 'PP1CS000', # PP1CS000?
'te' => 'PP2CS000', # PP2CS000?
'se' => 'PP3CN000', # PP3CN000? could be le|les => se or refl se ...or passive|impersonal se ...?
'nos' => 'PP1CP000', # PP1CP000?
'os' => 'PP2CP000' # PP2CP000?
);
my %mapCliticFormToLemma = (
'la' => 'lo',
'las' => 'lo',
'lo' => 'lo',
'los' => 'lo',
'le' => 'le',
'les' => 'le',
'me' => 'me',
'te' => 'te',
'se' => 'se',
'nos' => 'nos',
'os' => 'os'
);
# read conll file and create xml (still flat)
my $scount=1; #sentence ord
my %docHash;
my %conllHash; # hash to store each sentence as conll, in case second analysis is needed
my $dom = XML::LibXML->createDocument ('1.0', 'UTF-8');
my $root = $dom->createElementNS( "", "corpus" );
$dom->setDocumentElement( $root );
my $sentence; # actual sentence
# necessary to differentiate between opening and closing quotes, tagger doesn't do that
my $openQuot=1;
my $openBar=1;
# my $verbose = '';
my ($file, $verbose, $withCorzu) = @ARGV;
my $InputLines = undef;
# print $InputLines;
# my $InputLines = $_[0];
# binmode($InputLines, ':utf8');
# $verbose = $_[1];
# my $withCorzu=$_[2];
print STDERR "#VERBOSE ". (caller(0))[3]."\n" if $verbose;
my $articleID ="";
my $sentInArticleID =1;
open(my $InputLines, '<:encoding(UTF-8)', $file) or die "Could not open file '$file' $!";
while(<$InputLines>)
{
#print "12\n";
my $line = $_;
# print $line;
# if($line =~ /ó|í|á/){print "matched line is: ".$line;
# my $encoding_name = Encode::Detect::Detector::detect($line);
# print "encoding is: ".$encoding_name."\n";
# }
# else{print "not matched line is: ".$line;}
#skip empty line
if($line =~ /^\s*$/)
{
$scount++;
undef $sentence;
}
# begin/end of document in conll: skip
elsif($line=~ /^#(begin|end) document/){
#only for evaluation
if(/\#begin document/){
($articleID) = ($_ =~ /\#begin document ([^\s]+)\.tbf/);
}
elsif(/\#end document/){
$articleID = "";
$sentInArticleID =1;
}
next;
}
# word with analysis
else
{
#create a new sentence node
if(!$sentence)
{
$sentence = XML::LibXML::Element->new( 'SENTENCE' );
$sentence->setAttribute( 'ord', $scount );
$root->appendChild($sentence);
$sentence->setAttribute( 'articleID', $articleID );
$sentence->setAttribute( 'sentInArticleID', $sentInArticleID );
$sentInArticleID++;
}
# create a new word node and attach it to sentence
my $wordNode = XML::LibXML::Element->new( 'NODE' );
$sentence->appendChild($wordNode);
my ($id, $word, $lem, $cpos, $pos, $info, $blank1, $blank2, $rel, $head, $rest) = split (/\t|\s+/, $line);
# entity: always last, but can be 9 or 10 columns -> just take last one
my @rows = split (/\t|\s/, $line);
my $entity = @rows[-1];
#print STDERR "line: $id, $word, $lem, $cpos, $pos, $info, $head, $rel, $phead, $prel\n";
# quotes, opening -> fea, closing -> fet
if($pos eq 'Fe')
{
# for some reason, apostrophes are not encoded by libxml -> leads to crash!
# -> replace them with quotes..
$word = '"';
$lem = '"';
if($openQuot){
$pos = 'Fea';
$openQuot=0;}
else{
$pos = 'Fet';
$openQuot=1;}
}
# hyphen, opening -> fga, closing -> fgt
if($pos eq 'Fg')
{
if($openQuot){
$pos = 'Fga';
$openBar=0;}
else{
$pos = 'Fgt';
$openBar=1;}
}
my ($eaglesTag) = ($info =~ /eagles=(.+)/);
# if verb (gerund,infinitve or imperative form) has clitic(s) then make new node(s)
if($eaglesTag =~ /^V.[GNM]/ and $word =~ /(me|te|nos|os|se|[^l](la|las|lo|los|le|les))$/ and $word !~ /parte|frente|adelante|base|menos$/ and $word !~ /_/)
{
#print STDERR "clitics in verb $lem: $word\n" if $verbose;
my $clstr = splitCliticsFromVerb($word,$eaglesTag,$lem);
if ($clstr !~ /^$/){ # some imperative forms may end on "me|te|se|la|le" and not contain any clitic
&createAppendCliticNodes($sentence,$scount,$id,$clstr);
}
}
if($eaglesTag =~ /^NP/){
$pos="np";
}
# set rel of 'y' and 'o' to coord
if($lem eq 'y' || $lem eq 'o'){
$rel = 'coord';
}
# often: 'se fue' -> fue tagged as 'ser', VSIS3S0 -> change to VMIS3S0, set lemma to 'ir'
if($eaglesTag =~ /VSIS[123][SP]0/ && $lem eq 'ser'){
my $precedingWord = $docHash{$scount.":".($id-1)};
#print STDERR "preceding of fue: ".$precedingWord->getAttribute('lem')."\n" if $verbose;
if($precedingWord && $precedingWord->getAttribute('lem') eq 'se'){
$eaglesTag =~ s/^VS/VM/ ;
#print STDERR "new tag: $eaglesTag\n" if $verbose;
$lem = 'ir';
}
}
# # if 'hay' tagged as VA -> changed to VM!
# if($eaglesTag eq 'VAIP3S0' && $word =~ /^[Hh]ay$/){
# $eaglesTag = 'VMIP3S0' ;
# print STDERR "new tag for hay: $eaglesTag\n" if $verbose;
# }
# freeling error for reirse, two lemmas, reír/reir -> change to reír
if($lem =~ /\/reir/){
$lem = 'reír';
}
$wordNode->setAttribute( 'ord', $id );
$wordNode->setAttribute( 'form', $word );
$wordNode->setAttribute( 'lem', $lem );
$wordNode->setAttribute( 'pos', lc($pos) );
$wordNode->setAttribute( 'cpos', $cpos );
$wordNode->setAttribute( 'head', $head );
$wordNode->setAttribute( 'rel', $rel );
if($eaglesTag eq ''){
$wordNode->setAttribute( 'mi', $pos );
}
else{
$wordNode->setAttribute( 'mi', $eaglesTag );
}
unless($entity eq '_' or $entity eq ''){
$wordNode->setAttribute('entityTokenLevel', $entity);
}
# print "$eaglesTag\n";
# store node in hash, key sentenceId:wordId, in order to resolve dependencies
my $key = "$scount:$id";
$docHash{$key}= $wordNode;
$conllHash{$scount} = $conllHash{$scount}.$line;
}
}
#my $docstring = $dom->toString(3);
#print STDERR $docstring;
## adjust dependencies (word level),
my @sentences = $dom->getElementsByTagName('SENTENCE');
#foreach my $sentence ( $dom->getElementsByTagName('SENTENCE'))
for(my $i = 0; $i < scalar(@sentences); $i++)
{
my $sentence = @sentences[$i];
my $sentenceId = $sentence->getAttribute('ord');
print STDERR "adjusting dependencies in sentence: ".$sentence->getAttribute('ord')."\n" if $verbose;
#print STDERR "2: ".$sentence->toString."\n" if $verbose;
my @nodes = $sentence->getElementsByTagName('NODE');
foreach my $node (@nodes)
{
#print STDERR $node->getAttribute('ord')."\n" if $verbose;
my $head = $node->getAttribute('head');
if ($head ne '0')
{
my $headKey = "$sentenceId:$head";
#print STDERR "Head key: $headKey\n" if $verbose;
my $word = $node->getAttribute('form');
#print "$word= $headKey\n";
my $parent = $docHash{$headKey};
eval
{
$parent->appendChild($node);
}
or do
{
print STDERR "loop detected in sentence: ".$sentence->getAttribute('ord')."\n" if $verbose;
$i--;
last;
}
}
# if this is the head, check if it's a good head (should not be a funcion word!), and if not,
# check if there are >3 words in this sentence (otherwise it might be a title)
# else
# {
# my $pos = $node->getAttribute('pos');
#
# if($pos =~ /d.|s.|p[^I]|c.|n.|r.|F./ && scalar(@nodes) > 4)
# {
# $i--;
# last;
# }
# }
}
}
# my $docstring = $dom->toString(3);
# print STDERR $docstring;
if($verbose){
my $docstring = $dom->toString(3);
print STDERR $docstring if $verbose;
print STDERR "------------------------------------------------\n";
print STDERR "------------------------------------------------\n";
}
# # insert chunks
#
foreach my $sentence ( $dom->getElementsByTagName('SENTENCE'))
{
my $sentenceId = $sentence->getAttribute('ord');
#print STDERR "insert chunks in sentence: $sentenceId\n" if $verbose;
#my $chunkCount = 1;
my $parent;
my @nodes = $sentence->getElementsByTagName('NODE');
my $nonewChunk = 0;
for(my $i=0; $i<scalar(@nodes); $i++)
{
#my $docstring = $dom->toString(3);
my $node = @nodes[$i];
my $head = $node->getAttribute('head');
my $headKey = "$sentenceId:$head";
my $word = $node->getAttribute('form');
#print STDERR "node at $i: ".$node->toString()."\n" if $verbose;
if ($head ne '0')
{
#print "$word= $headKey\n";
$parent = $docHash{$headKey};
# in case no parent found, assume parent is sentence (this shouldn't happen)
if(!$parent)
{
$parent = $sentence;
}
}
#if head of sentence, parent is sentence node
else
{
$parent = $sentence;
}
#if this is a main verb or auxiliary used as main verb
# (as auxiliary rel=v, auxilaries don't get their own chunk, they should live inside the main verbs' chunk)
# if this is a finite verb with rel=v, check if its a finite verb and head is non-finite
# -> avoid having two finite verbs in one chunk!
if ($node->exists('self::NODE[starts-with(@mi,"V")] and not(self::NODE[@rel="v"])') )
{
my $verbchunk = XML::LibXML::Element->new( 'CHUNK' );
#if this node is parent of a coordination
if ($node->exists('child::NODE[@lem="ni" or @rel="coord"]'))
{
$verbchunk->setAttribute('type', 'coor-v');
}
# no coordination
else
{
$verbchunk->setAttribute('type', 'grup-verb');
}
# if this is the main verb in the chunk labeled as VA, change pos to VM
if($node->getAttribute('pos') eq 'va' && !$node->exists('child::NODE[@pos="vm"]'))
{
my $eaglesTag = $node->getAttribute('mi');
substr($eaglesTag, 1, 1) = "M";
$node->setAttribute('mi',$eaglesTag);
$node->setAttribute('pos', 'vm');
print STDERR "changed mi of ".$node->{'form'}." to $eaglesTag\n" if $verbose;
}
# head of rel-clause as suj to rel-clause-verb
# Maltparser: La mujer a quien vieron ya no vive aquí.
# <SENTENCE ord="1">
# <NODE ord="5" form="vieron" lem="ver" pos="vm" cpos="v" head="0" rel="sentence" mi="VMIS3P0">
# <NODE ord="2" form="mujer" lem="mujer" pos="nc" cpos="n" head="5" rel="suj" mi="NCFS000">
# <NODE ord="1" form="La" lem="el" pos="da" cpos="d" head="2" rel="spec" mi="DA0FS0"/>
# </NODE>
# <NODE ord="3" form="a" lem="a" pos="sp" cpos="s" head="5" rel="cc" mi="SPS00">
# <NODE ord="4" form="quien" lem="quien" pos="pr" cpos="p" head="3" rel="sn" mi="PR0CS000"/>
# </NODE>
# <NODE ord="6" form="ya" lem="ya" pos="rg" cpos="r" head="5" rel="cc" mi=""/>
# <NODE ord="8" form="vive" lem="vivir" pos="vm" cpos="v" head="5" rel="cd" mi="VMIP3S0">
# <NODE ord="7" form="no" lem="no" pos="rn" cpos="r" head="8" rel="mod" mi="RN"/>
# <NODE ord="9" form="aquí" lem="aquí" pos="rg" cpos="r" head="8" rel="cc" mi=""/>
# </NODE>
# <NODE ord="10" form="." lem="." pos="fp" cpos="F" head="5" rel="f" mi="Fp"/>
# </NODE>
# </SENTENCE>
# find rel-prn within PP
my $relprn = ${$node->findnodes('NODE[@pos="sp"]/NODE[starts-with(@mi,"PR")]')}[-1];
my $subj = ${$node->findnodes('../descendant::*[(@rel="suj" or @rel="cd-a") and @cpos="n"][1]')}[0];
#check if subj should be the head of the rel-clause (head preceeds rel-prn)
if($relprn && $subj && ( $relprn->getAttribute('ord') > $subj->getAttribute('ord') && &preceedNoVerbinBetween($subj,$node) ))
{
$node->setAttribute('head', $subj->getAttribute('ord'));
$head = $subj->getAttribute('ord');
$node->setAttribute('rel', 'S');
$parent->appendChild($subj);
$subj->appendChild($node);
if($parent->nodeName() eq 'SENTENCE')
{
$subj->setAttribute('si', 'top');
$subj->setAttribute('head', '0');
}
else
{
if($parent->nodeName() eq 'NODE')
{
$subj->setAttribute('head', $parent->getAttribute('ord'));
}
else
{
$subj->setAttribute('head', $parent->getAttribute('ord'));
}
}
$parent=$subj;
}
# rel-clause attached to main verb instead of nominal head.... leave?
# <SENTENCE ord="1">
# <NODE ord="8" form="vive" lem="vivir" pos="vm" cpos="v" head="0" rel="sentence" mi="VMIP3S0">
# <NODE ord="2" form="mujer" lem="mujer" pos="nc" cpos="n" head="8" rel="suj" mi="NCFS000">
# <NODE ord="1" form="La" lem="el" pos="da" cpos="d" head="2" rel="spec" mi="DA0FS0"/>
# </NODE>
# <NODE ord="3" form="a" lem="a" pos="sp" cpos="s" head="8" rel="cd" mi="SPS00">
# <NODE ord="4" form="quien" lem="quien" pos="pr" cpos="p" head="3" rel="sn" mi="PR0CS000"/>
# </NODE>
# <NODE ord="5" form="dejaron" lem="dejar" pos="vm" cpos="v" head="8" rel="v" mi="VMIS3P0"/>
# <NODE ord="6" form="ya" lem="ya" pos="rg" cpos="r" head="8" rel="cc" mi=""/>
# <NODE ord="7" form="no" lem="no" pos="rn" cpos="r" head="8" rel="mod" mi="RN"/>
# <NODE ord="9" form="aquí" lem="aquí" pos="rg" cpos="r" head="8" rel="cc" mi=""/>
# <NODE ord="10" form="." lem="." pos="fp" cpos="F" head="8" rel="f" mi="Fp"/>
# </NODE>
# </SENTENCE>
# if this verb is labeled as 'suj', but is local person -> change label to 'S'
if($node->getAttribute('rel') eq 'suj' && $node->getAttribute('mi') =~ /1|2/ )
{
$node->setAttribute('rel','S');
}
# if this is a gerund labeled as 'suj' with no verbal child node -> change label to 'cc'
elsif($node->getAttribute('rel') eq 'suj' && $node->getAttribute('mi') =~ /^VMG/ && !$node->exists('child::NODE[@lem="estar"]'))
{
$node->setAttribute('rel','gerundi');
}
#if this verb chunk is labeled as 'cd' but main verb has no 'que' and this is not an infinitive: change label to 'S'
elsif($node->getAttribute('rel') eq 'cd' && $node->getAttribute('mi') !~ /^V[MAS]N/ && !$parent->exists('descendant::NODE[@lem="que"]' ))
{
$node->setAttribute('rel','S');
}
# relative clauses: if head of verbchunk is a nominal chunk + verbchunk has descendant = relative pronoun -> set si="S"
if($node->exists('parent::NODE[@cpos="n"]') && $node->exists('child::NODE[@pos="pr"]'))
{
$verbchunk->setAttribute('si', 'S');
}
else
{
$verbchunk->setAttribute('si', $node->getAttribute('rel'));
}
$verbchunk->setAttribute('ord', $node->getAttribute('ord'));
#$node->removeAttribute('rel');
$node->removeAttribute('head');
$verbchunk->appendChild($node);
eval{$parent->appendChild($verbchunk);};
warn "could not attach verbchunk".$node->getAttribute('ord')."to head in sentence: $sentenceId" if $@;
# the key in hash should point now to the chunk instead of the node
my $ord = $node->getAttribute('ord');
my $idKey = "$sentenceId:$ord";
$docHash{$idKey}= $verbchunk;
}
# if this is a noun, a personal or a demonstrative pronoun, or a number, make a nominal chunk (sn)
# change 13.04.2015: put PT (interrogative non-attributive pronouns) in their own chunk, so they can be moved independently of the verb
elsif ($node->exists('self::NODE[@cpos="n" or @pos="pp" or @pos="pd" or @pos="pi" or @pos="Z" or @pos="pt"]'))
{
my $nounchunk = XML::LibXML::Element->new( 'CHUNK' );
#if this node is parent of a coordination
if ($node->exists('child::NODE[@lem="ni" or @rel="coord"]'))
{
$nounchunk->setAttribute('type', 'coor-n');
# if coordinated prsprn -> mostly wrong-> correct
if($node->getAttribute('pos') eq 'pp')
{
&correctCoord($node, $sentenceId);
}
}
# no coordination
else
{
$nounchunk->setAttribute('type', 'sn');
}
#print STDERR "node: ".$node->getAttribute('lem')." ,parent: ".$parent->toString."\n" if $verbose;
# if this is suj -> check if congruent with finite verb, check also if parent is a verbchunk
if($node->getAttribute('rel') eq 'suj' && $parent->exists('self::*[@type="grup-verb" or @cpos="v" or @type="coor-v"]') && &isCongruent($node, $parent) == 0)
{ #print STDERR "dom: ".$dom->toString(2)."\n";
$node->setAttribute('rel', 'cd-a');
}
# if this is 'lo/la' and pp-> change to cd
if($node->getAttribute('lem') eq 'lo')
{
$node->setAttribute('rel', 'cd');
}
# if this is 'le' and pp-> change to ci
elsif($node->getAttribute('lem') eq 'le')
{
$node->setAttribute('rel', 'ci');
}
# if this is tú/yo/ etc and congruent with verb -> this is the subject
#if($node->getAttribute('lem') =~ /^yo|tú|él|ellos|nosotros|vosotros/ && $parent->exists('self::*[@type="grup-verb" or @cpos="v"]') && &isCongruent($node,$parent) ==1 )
# problem: STDIN is set to :utf8, libxml doesn't like that, can't match tú/él directly
if($node->getAttribute('mi') =~ /PP2CSN0.|PP3.S000/ && $parent->exists('self::*[@type="grup-verb" or @cpos="v"]') && &isCongruent($node,$parent))
{
$node->setAttribute('rel', 'suj-a');
}
elsif($node->getAttribute('lem') =~ /^yo|ellos|nosotros|vosotros/ && $parent->exists('self::*[@type="grup-verb" or @cpos="v"]') && &isCongruent($node,$parent) )
{
$node->setAttribute('rel', 'suj-a');
}
$nounchunk->setAttribute('si', $node->getAttribute('rel'));
$nounchunk->setAttribute('ord', $node->getAttribute('ord'));
#$node->removeAttribute('rel');
$node->removeAttribute('head');
$nounchunk->appendChild($node);
$parent = &attachNewChunkUnderChunk($nounchunk,$parent,$sentence); # $parent->appendChild($nounchunk);
# the key in hash should point now to the chunk instead of the node
my $ord = $node->getAttribute('ord');
my $idKey = "$sentenceId:$ord";
$docHash{$idKey}= $nounchunk;
#check if there are already child chunks attached (corrected rel. clauses), if so, attach them to noun chunk
for my $chunkchild ($node->getElementsByTagName('CHUNK'))
{
$nounchunk->appendChild($chunkchild);
}
}
# if this is a preposition, make a prepositional chunk (grup-sp)
elsif ($node->exists('self::NODE[starts-with(@mi,"SP")]'))
{
#print STDERR "parent of prep: \n".$parent->toString."\n" if $verbose;
# if head is an infinitive (para hacer, voy a hacer, de hacer etc)-> don't create a chunk, preposition just hangs below verb
# check if preposition precedes infinitive, otherwise make a chunk
if($parent->exists('self::CHUNK/NODE[@mi="VMN0000" or @mi="VSN0000"]') && $parent->getAttribute('ord')> $node->getAttribute('ord'))
{
}
else
{
my $ppchunk = XML::LibXML::Element->new( 'CHUNK' );
#if this node is parent of a coordination
if ($node->exists('child::NODE[@lem="ni" or @rel="coord"]'))
{
$ppchunk->setAttribute('type', 'coor-sp');
}
# no coordination
else
{
$ppchunk->setAttribute('type', 'grup-sp');
}
my $rel = $node->getAttribute('rel');
# check if preposition has been labeled as subject -> happens in dates since maltparser hasnt learned how to parse those splitted (multitokens in ancora)
# -> change label to atr
if($rel eq 'suj'){
$rel = 'atr';
}
elsif($rel eq 'cd' && $node->getAttribute('lem') ne 'a'){
$rel = 'cc';
}
$ppchunk->setAttribute('si', $rel);
$ppchunk->setAttribute('ord', $node->getAttribute('ord'));
#$node->removeAttribute('rel');
$node->removeAttribute('head');
$ppchunk->appendChild($node);
$parent->appendChild($ppchunk);
# the key in hash should point now to the chunk instead of the node
my $ord = $node->getAttribute('ord');
my $idKey = "$sentenceId:$ord";
$docHash{$idKey}= $ppchunk;
}
}
# if this is an adjective, make an adjective chunk (sa)
elsif ($node->exists('self::NODE[starts-with(@mi,"A")]'))
{
my $sachunk = XML::LibXML::Element->new( 'CHUNK' );
#if this node is parent of a coordination
if ($node->exists('child::NODE[@lem="ni" or @rel="coord"]'))
{
$sachunk->setAttribute('type', 'coor-sa');
}
# no coordination
else
{
$sachunk->setAttribute('type', 'sa');
}
$sachunk->setAttribute('si', $node->getAttribute('rel'));
$sachunk->setAttribute('ord', $node->getAttribute('ord'));
#$node->removeAttribute('rel');
$node->removeAttribute('head');
$sachunk->appendChild($node);
$parent = &attachNewChunkUnderChunk($sachunk,$parent,$sentence);
#$parent->appendChild($sachunk);
# the key in hash should point now to the chunk instead of the node
my $ord = $node->getAttribute('ord');
my $idKey = "$sentenceId:$ord";
$docHash{$idKey}= $sachunk;
}
# if this is an adverb, make an adverb chunk (sadv)
elsif ($node->exists('self::NODE[starts-with(@mi,"R")]'))
{
my $sadvchunk = XML::LibXML::Element->new( 'CHUNK' );
#if this node is parent of a coordination
if ($node->exists('child::NODE[@lem="ni" or @rel="coord"]'))
{
$sadvchunk->setAttribute('type', 'coor-sadv');
}
# no coordination
else
{
$sadvchunk->setAttribute('type', 'sadv');
}
$sadvchunk->setAttribute('si', $node->getAttribute('rel'));
$sadvchunk->setAttribute('ord', $node->getAttribute('ord'));
#$node->removeAttribute('rel');
$node->removeAttribute('head');
$sadvchunk->appendChild($node);
$parent = &attachNewChunkUnderChunk($sadvchunk,$parent,$sentence);
#if ($parent->nodeName eq 'NODE') {
# print STDERR "adverb chunk" . $sadvchunk->toString(). " within NODE ". $parent->toString() ." has to be appended to a higher CHUNK\n" if $verbose;
# $parent = @{$parent->findnodes('ancestor::CHUNK[1]')}[0];
#}
#$parent->appendChild($sadvchunk);
# the key in hash should point now to the chunk instead of the node
my $ord = $node->getAttribute('ord');
my $idKey = "$sentenceId:$ord";
$docHash{$idKey}= $sadvchunk;
}
# if this is a subordination (CS), check if attached to correct verb (gets often attached to main clause instead of subordinated verb)
elsif($node->getAttribute('pos') eq 'cs' && !$parent->exists('child::NODE[@pos="vs"]') )
{
&attachCSToCorrectHead($node, $sentence);
}
# if this is punctuation mark
elsif ($node->exists('self::NODE[starts-with(@mi,"F")]'))
{
my $fpchunk = XML::LibXML::Element->new( 'CHUNK' );
$fpchunk->setAttribute('type', 'F-term');
$fpchunk->setAttribute('si', 'term');
$fpchunk->setAttribute('ord', $node->getAttribute('ord'));
$node->removeAttribute('rel');
$node->removeAttribute('head');
$fpchunk->appendChild($node);
# if punctuation has childnodes -> wrong, append those to parent of punctuation mark
# unless this is the head of the sentence, in this case make first verb head of sentence
if($parent->nodeName eq 'SENTENCE')
{
my $realMainVerb = @{$node->findnodes('child::NODE[@cpos="v" and not(@rel="v")][1]')}[0];
my $firstchild = @{$node->findnodes('child::NODE[not(@cpos="F")][1]')}[0];
if($realMainVerb)
{
$parent->appendChild($realMainVerb);
$realMainVerb->setAttribute('head', '0');
$parent = $realMainVerb;
}
# else, no main verb (this is a title), take first child as head of sentence
elsif($firstchild)
{
$parent->appendChild($firstchild);
$firstchild->setAttribute('head', '0');
$parent = $firstchild;
}
# else: sentence consists only of punctuation marks?
# append to Chunk and leave as is..
else
{
$fpchunk->appendChild($node);
eval {$parent->appendChild($fpchunk);};
warn "could not append punctuation chunk to parent chunk".$node->getAttribute('ord')." in sentence: $sentenceId" if $@;
next;
}
}
my @children = $node->childNodes();
foreach my $child (@children)
{
{ eval
{
$parent->appendChild($child);
$child->setAttribute('head', $parent->getAttribute('ord'));
};
warn "could not reattach child of punctuation chunk".$node->getAttribute('ord')." in sentence: $sentenceId" if $@;
}
}
eval {$parent->appendChild($fpchunk);};
warn "could not append punctuation chunk to parent chunk".$node->getAttribute('ord')." in sentence: $sentenceId" if $@;
# the key in hash should point now to the chunk instead of the node
my $ord = $node->getAttribute('ord');
my $idKey = "$sentenceId:$ord";
$docHash{$idKey}= $fpchunk;
}
# if this is a date
elsif ($node->exists('self::NODE[@mi="W"]') or ( $node->exists('self::NODE[@mi="Z"]') && &numberIsPartOfDate($node) ) )
{
my $datechunk = XML::LibXML::Element->new( 'CHUNK' );
$datechunk->setAttribute('type', 'date');
$datechunk->setAttribute('si', $node->getAttribute('rel'));
$datechunk->setAttribute('ord', $node->getAttribute('ord'));
$node->removeAttribute('rel');
$node->removeAttribute('head');
$datechunk->appendChild($node);
$parent->appendChild($datechunk);
# the key in hash should point now to the chunk instead of the node
my $ord = $node->getAttribute('ord');
my $idKey = "$sentenceId:$ord";
$docHash{$idKey}= $datechunk;
}
# if this is an interjection
elsif ($node->exists('self::NODE[@mi="I"]'))
{
my $interjectionchunk = XML::LibXML::Element->new( 'CHUNK' );
$interjectionchunk->setAttribute('type', 'interjec');
$interjectionchunk->setAttribute('si', $node->getAttribute('rel'));
$interjectionchunk->setAttribute('ord', $node->getAttribute('ord'));
$node->removeAttribute('rel');
$node->removeAttribute('head');
$interjectionchunk->appendChild($node);
$parent->appendChild($interjectionchunk);
# the key in hash should point now to the chunk instead of the node
my $ord = $node->getAttribute('ord');
my $idKey = "$sentenceId:$ord";
$docHash{$idKey}= $interjectionchunk;
}
else
{
#if this is a chunk
if($node->nodeName() eq 'CHUNK')
{
$parent->appendChild($node);
}
}
# set si of root to 'top'
if($head eq '0')
{
my $chunkparent = $node->parentNode();
if($chunkparent && $chunkparent->exists('self::CHUNK') )
{
$chunkparent->setAttribute('si', 'top');
$chunkparent->setAttribute('ord', $node->getAttribute('ord'));
}
}
}
# #my $docstring = $dom->toString(3);
# #print STDERR $docstring;
# #print STDERR "\n------------------------\n";
#
# sentence complete: check if topnode is a CHUNK, if not, change this
# otherwise lexical transfer crashes!
if($sentence->exists('child::NODE'))
{
&moveTopNodeUnderChunk($sentence);
}
# soler+inf -> inf as cd -> change
# <SENTENCE ord="1">
# <CHUNK type="grup-verb" si="top" ord="1">
# <NODE ord="1" form="Solían" lem="soler" pos="vm" cpos="v" rel="sentence" mi="VMII3P0"/>
# <CHUNK type="grup-verb" si="cd" ord="2">
# <NODE ord="2" form="dormir" lem="dormir" pos="vm" cpos="v" rel="cd" mi="VMN0000"/>
# <CHUNK type="sadv" si="cc" ord="3">
# <NODE ord="3" form="temprano" lem="temprano" pos="rg" cpos="r" rel="cc" mi="RG"/>
# </CHUNK>
# </CHUNK>
# <CHUNK type="F-term" si="term" ord="4">
# <NODE ord="4" form="." lem="." pos="fp" cpos="F" mi="Fp"/>
# </CHUNK>
# </CHUNK>
# </SENTENCE>
my @solerswithCD = $sentence->findnodes('descendant::CHUNK[(@type="grup-verb" or @type="coor-v") and NODE[@lem="soler"] and CHUNK[(@type="grup-verb" or @type="coor-v") and @si="cd"]/NODE[@mi="VMN0000"] ]');
if(scalar(@solerswithCD)>0){
foreach my $solerchunk (@solerswithCD){
my ($inf) = $solerchunk->findnodes('child::CHUNK[(@type="grup-verb" or @type="coor-v") and @si="cd" and NODE[@mi="VMN0000"] ]');
if($inf){
my $inford = $inf->findvalue('child::NODE[@mi="VMN0000"]/@ord');
my $solerord = $solerchunk->findvalue('child::NODE[@lem="soler"]/@ord');
if($solerord+1 == $inford){
my $solerparent = $solerchunk->parentNode();
my ($solernode) = $solerchunk->findnodes('child::NODE[@lem="soler"]');
my ($infnode) = $inf->findnodes('child::NODE[@mi="VMN0000"]');
if($solerparent && $solernode && $infnode){
$infnode->appendChild($solernode);
$solernode->setAttribute('rel', 'v');
$solerparent->appendChild($inf);
my @solerchildren = $solerchunk->childNodes();
foreach my $solerchild(@solerchildren){
$inf->appendChild($solerchild);
}
$inf->setAttribute('si', $solerchunk->getAttribute('si'));
$solerparent->removeChild($solerchunk);
}
}
#print STDERR "ord soler $solerord, ord inf: $inford\n";
}
}
}
# if there is a main verb in the chunk labeled as VA with a child node VMG -> make gerund head!
my @falseAux = $sentence->findnodes('descendant::CHUNK[(@type="grup-verb" or @type="coor-v") and NODE[(@lem="estar" and @pos="va") or @lem="ser"] and CHUNK[NODE[@mi="VMG0000"]] ]');
if(scalar(@falseAux) > 0)
{
foreach my $aux (@falseAux)
{
my ($gerund) = $aux->findnodes('child::CHUNK[NODE[@mi="VMG0000"]][1]');
if($gerund)
{
my ($gerundnode) = $gerund->findnodes('child::NODE[@mi="VMG0000"][1]');
my ($auxnode) = $aux->findnodes('child::NODE[@lem="estar" or @lem="ser"]');
my $parent = $aux->parentNode();
$parent->appendChild($gerund);
my @auxchildren = $aux->childNodes();
$parent->removeChild($aux);
foreach my $child(@auxchildren){
$gerund->appendChild($child);
}
$gerundnode->appendChild($auxnode);
$auxnode->setAttribute('rel', 'v');
$gerund->setAttribute('si', $aux->getAttribute('si'));
}
}
}
# ir a +infinitive
# <CHUNK type="grup-verb" si="top" ord="1">
# <NODE ord="1" form="Van" lem="ir" pos="vm" cpos="v" rel="sentence" mi="VMIP3P0"/>
# <CHUNK type="grup-verb" si="S" ord="3">
# <NODE ord="3" form="pensarlo" lem="pensar" pos="vm" cpos="v" rel="S" mi="VMN0000">
# <NODE ord="2" form="a" lem="a" pos="sp" cpos="s" head="3" rel="s" mi="SPS00"/>
# </NODE>
my @irAinf = $sentence->findnodes('descendant::CHUNK[(@type="grup-verb" or @type="coor-v") and NODE[@lem="ir"] and CHUNK[(@type="grup-verb" or @type="coor-v") and NODE[@mi="VMN0000" and NODE[@lem="a"] ] ] ]');
if(scalar(@irAinf)>0){
foreach my $ir (@irAinf){
my ($inf) = $ir->findnodes('child::CHUNK[(@type="grup-verb" or @type="coor-v") and NODE[@mi="VMN0000" and NODE[@lem="a"]] ]');
if($inf){
my $parent = $ir->parentNode();
my ($irnode) = $ir->findnodes('child::NODE[@lem="ir"][1]');
my ($infnode) = $inf->findnodes('child::NODE[@mi="VMN0000"][1]');
$parent->appendChild($inf);
my @irchildren = $ir->childNodes();
$parent->removeChild($ir);
foreach my $irchild (@irchildren){
$infnode->appendChild($irchild);
}
$infnode->appendChild($irnode);
}
}
}
# check if main verb is in fact a subordinated clause, if so, make second grup-verb head
# if coordinated vp: don't take first child grup-verb (this is the coordinated vp), take the last
# note: if parser made something else head of sentence, the top verb might not have si=top
my $topverbchunk = @{$sentence->findnodes('child::CHUNK[(@type="grup-verb" or @type="coor-v") and @si="top"][1]')}[0];
#my $topverbchunk = @{$sentence->findnodes('child::CHUNK[(@type="grup-verb" or @type="coor-v")][1]')}[0];
if($topverbchunk && $topverbchunk->exists('child::NODE[@cpos="v"]/descendant::NODE[@pos="cs"]'))
{ print STDERR "in sentence $sentenceId, top chunk is".$topverbchunk->getAttribute('ord')."\n" if $verbose;
my $realMain = @{$topverbchunk->findnodes('child::CHUNK[@type="grup-verb" or @type="coor-v"]/NODE[@cpos="v" and not(child::NODE[@pos="cs"])]')}[-1];
if($realMain)
{
print STDERR "real main verb: ".$realMain->toString() if $verbose;
$topverbchunk->parentNode->appendChild($realMain->parentNode());
$realMain->parentNode()->appendChild($topverbchunk);
$topverbchunk->setAttribute('si', 'S');
$realMain->parentNode->setAttribute('si', 'top');
}
}
my @verbchunks = $sentence->findnodes('descendant::CHUNK[@type="grup-verb" or @type="coor-v"]');
foreach my $verbchunk (@verbchunks)
{
# check if one of the verbs in this sentence has more than one subject (can happen with statistical parsers!), if only one is congruent with the verb, make this the subject
# and the other 'cd-a', if more than one is congruent, make the first one the subject (the one that precedes the verb)
# simpler: check if first subject is congruent, if not, check next etc
my @subjectNodes = $verbchunk->findnodes('child::CHUNK[@si="suj"]/NODE[@rel="suj"]');
if(scalar(@subjectNodes) > 1)
{
#print STDERR "verb chunk ord: ".$verbchunk->getAttribute('ord'). "\n" if $verbose;
my %subjs =();
foreach my $subjCand (@subjectNodes)
{
my $ord = $subjCand->getAttribute('ord');
$subjs{$ord} = $subjCand;
print STDERR "to many subjects: ".$subjCand->getAttribute('lem')." ord: ".$ord."\n" if $verbose;
}
my $candIsSubj = 0;
foreach my $ord (sort {$a<=>$b} (keys (%subjs)))
{
my $subjCand = $subjs{$ord};
if(&isCongruent($subjCand,$verbchunk) && $candIsSubj == 0)
{
print STDERR "correct subj: ".$subjCand->getAttribute('lem')."\n" if $verbose;
$candIsSubj =1;
}
else
{
$subjCand->parentNode->setAttribute('si', 'cd-a');
$subjCand->setAttribute('rel', 'cd-a');
}
#print STDERR "sorted lemma subj: ".$subjCand->getAttribute('lem')." ord: ".$ord."\n" if $verbose;
}
}
}
# check if all chunks are children of chunks (if nodes have child chunks, the lexical transfer module is not amused)
foreach my $chunk ($sentence->getElementsByTagName('CHUNK'))
{
if($chunk->parentNode->nodeName eq 'NODE')
{
my $realparent = @{$chunk->findnodes('ancestor::CHUNK[1]')}[0];
if($realparent){
$realparent->appendChild($chunk);
}
else{
$sentence->appendChild($chunk);
}
}
}
# make sure no chunk has a sibling node, lexical transfer module doesn't like that either
my @nodesWithChunkSiblings = $sentence->findnodes('descendant::NODE[preceding-sibling::CHUNK]');
foreach my $node (@nodesWithChunkSiblings)
{ # print STDERR "node sibl: ".$node->toString()."\n" if $verbose;
# if CC or CS -> try to attach it to the following verb chunk, if that fails to the preceding
# if there's no verb chunk, attach it to the next higher chunk (probably an error by the tagger, but let's try to avoid
# making the lexical transfer fail)
# NOTE: no need to copy children of sibling, as NODE with child CHUNKS have already been taken care of above
my $possibleHead = @{$node->findnodes('ancestor::CHUNK[@type="grup-verb" or @type="coor-v"]/NODE/descendant-or-self::NODE')}[0];
my $possibleHead2 = @{$node->findnodes('descendant::CHUNK[@type="grup-verb" or @type="coor-v"]/NODE/descendant-or-self::NODE')}[0];
if($possibleHead){
$possibleHead->appendChild($node);
}
elsif($possibleHead2){
$possibleHead->appendChild($node);
}
else{
$possibleHead = @{$node->findnodes('ancestor::SENTENCE/CHUNK[@si="top"]/NODE/descendant-or-self::NODE')}[0];
#print $possibleHead->toString()."\n\n";
if($possibleHead){
$possibleHead->appendChild($node);
}
}
}
# make sure nodes have no (node) siblings, again, lexical transfer module will crash
# solution: attach second sibling as (last) child of first
my @nodesWithNodeSiblings = $sentence->findnodes('descendant::NODE[preceding-sibling::NODE]');
foreach my $node (@nodesWithNodeSiblings){
my $prevsibling = $node->previousSibling();
if($prevsibling){
if ($prevsibling->getAttribute('mi') =~ /V...[1-3][SP]./) { # finite
$node->appendChild($prevsibling);
} else {
$prevsibling->appendChild($node);
}
}
}
# delete chunks that have only chunk children, but no node children (otherwise lexical transfer crashes)
# -> those are probably leftovers from changes to the tree, should not occur
my @chunksWithNoNODEchildren = $sentence->findnodes('descendant::CHUNK[count(child::NODE)=0]');
foreach my $chunk (@chunksWithNoNODEchildren){
my $parentchunk = $chunk->parentNode();
if($parentchunk && $parentchunk->nodeName eq 'CHUNK'){
# attach this chunks' chunk children to its parent chunk, then delete it
my @childChunks = $chunk->childNodes();
foreach my $child (@childChunks){
$parentchunk->appendChild($child);
}
$parentchunk->removeChild($chunk);
}
}
# make sure final punctuation (.!?) is child of top chunk, if not, append to top chunk
# -> otherwise punctuation will appear in some random position in the translated output!
# TODO: ! and ? -> direct speech!!
# my @finalPunc = $sentence->findnodes('descendant::NODE[@lem="." or @lem="!" or @lem="?"]');
my @finalPunc = $sentence->findnodes('descendant::NODE[@lem="."]');
foreach my $punc (@finalPunc){
if(isLastNode($punc,$sentence) && !$punc->exists('parent::CHUNK/parent::SENTENCE') ){
my $topchunk = @{$sentence->findnodes('child::CHUNK[1]')}[0];
my $puncChunk = $punc->parentNode();
if($topchunk && $puncChunk){
$topchunk->appendChild($puncChunk);
}
}
}
# if there's a sólo/solamente -> find right head
# parser ALWAYS attaches this to the verb, but that may not be correct,
# e.g. 'Sólo Juan sabe lo que ha hecho.' TODO: nomás!
if( $sentence->exists('descendant::NODE[@lem="sólo" or @lem="sólamente"]') )
{
my @solos = $sentence->findnodes('descendant::NODE[@lem="sólo" or @lem="sólamente"]');