-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextFileHandler.java
More file actions
1200 lines (887 loc) · 30.5 KB
/
Copy pathTextFileHandler.java
File metadata and controls
1200 lines (887 loc) · 30.5 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
package com.deft.sarcasm.train;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import org.apache.commons.lang3.StringUtils;
import com.deft.sarcasm.features.BoWFeatureLoader;
import com.deft.sarcasm.features.EXPERIMENT_MODE;
import com.deft.sarcasm.features.LexicalPragFeatureLoader;
import com.deft.sarcasm.features.MPQAFeatureGenerator;
import com.deft.sarcasm.features.NonLexFeatureHandler;
import com.deft.sarcasm.features.PunctFeatureLoader;
import com.deft.sarcasm.features.WekaWriter;
import com.deft.sarcasm.train.SarcasmTrainHandler.unigramTypeEnum;
import com.deft.sarcasm.util.TextUtility;
//stanford classes
import edu.stanford.nlp.classify.Dataset;
import edu.stanford.nlp.classify.GeneralDataset;
import edu.stanford.nlp.classify.SVMLightClassifierFactory;
import edu.stanford.nlp.ling.BasicDatum;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.ling.Datum;
import edu.stanford.nlp.ling.Label;
import edu.stanford.nlp.ling.RVFDatum;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.POSTaggerAnnotator ;
import edu.stanford.nlp.process.Tokenizer;
import edu.stanford.nlp.tagger.maxent.MaxentTagger;
public class TextFileHandler
{
private HashMap<String, List<Map<Integer,Double>>> allFeatureMap;
private SarcasmResourceLoader sarcasmRLObject;
private BoWFeatureLoader bowFeatureObj;
private LexicalPragFeatureLoader lexFeatureObj;
private PunctFeatureLoader punctFeatureObj;
private String fileFormat;
private unigramTypeEnum unigramTypeEnum;
private TokenizerModel model;
private TokenizerME tokenizer;
private FileInputStream nlpStream;
private ArrayList<String> approvedFeatList;
private WekaWriter wekaWriterObj;
private String writingType;
private String wekaPath;
private Integer labelColumn;
private Integer msgColumn;
private ArrayList<String> positiveCat;
private ArrayList<String> negativeCat;
private MPQAFeatureGenerator sentimentObj;
private static final String POSITIVE_CAT = "1" ;
private static final String NEGATIVE_CAT = "0" ;
private enum FEATURE_TYPE
{
BINARY, COUNT
}
private enum FILE_FORMAT
{
SGML, TEXT
}
private enum FEATURE_SET
{
BOW, LIWC, POLARITY, PERIODS, ALTSPELL,WP,SENT
}
private static final String EOL = "\n" ;
private static Pattern ldcPattern = Pattern.compile("<DOC");
private static Pattern xmlParagraphPattern = Pattern.compile("<P\\s+sarcasm=\"(yes|no)\"\\s+pid=\"([0-9]+)\">([^<]+)");
private static final String OPENNLP_TOKENFILE = "en-token.bin" ;
public TextFileHandler(EXPERIMENT_MODE experMode) throws IOException
{
sarcasmRLObject = new SarcasmResourceLoader(experMode) ;
punctFeatureObj = new PunctFeatureLoader() ;
bowFeatureObj = new BoWFeatureLoader(experMode,sarcasmRLObject) ;
// new NonLexFeatureHandler(experMode,sarcasmRLObject);
lexFeatureObj = new LexicalPragFeatureLoader(sarcasmRLObject) ;
nlpStream = new FileInputStream("./data/config/" + OPENNLP_TOKENFILE );
sentimentObj = new MPQAFeatureGenerator () ;
}
/*
public void loadAllParaphraseFile () throws IOException
{
String path = "/Users/dg513/work/eclipse-workspace/nyucourse-workspace/NYUCourse/data/project/eval/" ;
File file = new File ( path);
File files[] = file.listFiles() ;
BufferedReader reader = null ;
for ( File f : files )
{
//moses op
if (f.getName().contains("phrase-table-moses-oppp-01052014.txt.only.OP.phrases") )
// if ( (f.getName().contains("ibm2_op_AMTResults_vote.txt")) || (f.getName().contains("moses_op_AMTResults_vote.txt")) )
{
reader = new BufferedReader ( new FileReader ( path + "/" + f.getName())) ;
String header = reader.readLine() ;
while ( true )
{
String line = reader.readLine() ;
if ( null == line )
{
break;
}
//0 1 <i willingly went to> <i was not conned into going to:0.375>
if (line.isEmpty())
{
continue ;
}
String features[] = line.split("\t") ;
String sarcasm = features[3] ;
sarcasm = sarcasm.substring(1,sarcasm.length()-1);
String msg = sarcasm.split(":")[0];
double probScore = Double.valueOf(sarcasm.split(":")[1]);
if(! (probScore>0.75) )
{
continue ;
}
features = msg.split("\\s++") ;
for ( int i = 0 ; i < features.length ; i++ )
{
for ( int j = i+1 ; j < features.length ; j++ )
{
String bigram = features[i] + "|||" + features[j] ;
bigram = bigram.toLowerCase();
if (!bigramList.contains(bigram) )
{
bigramList.add(bigram);
}
}
}
}
reader.close();
}
}
}
*/
public void loadSelectiveParaphraseFile () throws IOException
{
bowFeatureObj.loadSelectiveParaphraseFile();
}
//experiments on context/sarcasm - making it a different function since
//the data, parsing etc. will be little different
public void createFeaturesForContextTraining(String inputPath, String outputPath,String trainingFile, int context)
throws IOException, ClassNotFoundException
{
/*
String t = "John Bauer works at Stanford." ;
MaxentTagger maxentTagger = new MaxentTagger("./models/tagger/english-left3words-distsim.tagger");
POSTaggerAnnotator tagger = new POSTaggerAnnotator (maxentTagger);
Annotation ann = new Annotation(t);
String tagged = maxentTagger.tagString(t);
System.out.println(tagged);
tagger.annotate(ann);
*/
sentimentObj.init();
// createSentimentContextFeatures(inputPath,outputPath,trainingFile,EXPERIMENT_MODE.TRAINING, FEATURE_TYPE.BINARY,context) ;
createContextFeatures(inputPath,outputPath,trainingFile,EXPERIMENT_MODE.TRAINING, FEATURE_TYPE.BINARY,context) ;
// writeWekaArffFile(path,trainingFile,FEATURE_TYPE.BINARY);
}
public void createFeaturesForTraining(String inputPath, String outputPath,String trainingFile)
throws IOException, ClassNotFoundException
{
/*
String t = "John Bauer works at Stanford." ;
MaxentTagger maxentTagger = new MaxentTagger("./models/tagger/english-left3words-distsim.tagger");
POSTaggerAnnotator tagger = new POSTaggerAnnotator (maxentTagger);
Annotation ann = new Annotation(t);
String tagged = maxentTagger.tagString(t);
System.out.println(tagged);
tagger.annotate(ann);
*/
createFeatures(inputPath,outputPath,trainingFile,EXPERIMENT_MODE.TRAINING, FEATURE_TYPE.BINARY) ;
// writeWekaArffFile(path,trainingFile,FEATURE_TYPE.BINARY);
}
public void createSentimentContextFeatures ( String inputPath, String outputPath, String trainingFile,
EXPERIMENT_MODE experMode, FEATURE_TYPE featType, int context)
throws IOException, ClassNotFoundException
{
TextUtility.loadHashtags();
@SuppressWarnings("resource")
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(inputPath + "/" + trainingFile), "UTF8"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputPath + "/" + trainingFile + ".current.binary.svm."
+ experMode.toString() + "." + "txt.temp"),
"UTF8"));
System.out.println("PROCESSING: " + trainingFile) ;
int lineNumber = 1;
allFeatureMap = new HashMap<String,List<Map<Integer,Double>>>() ;
model = new TokenizerModel(nlpStream);
tokenizer = new TokenizerME(model);
while (true)
{
String line = reader.readLine();
if (null == line)
{
break;
}
// if ( lineNumber == 435)
// {
// System.out.println("here") ;
// }
String features[] = line.split("\t") ;
String label = features[labelColumn];//getLabel(trainingFile);
label = convert(label) ;
// String target = features[1].trim();
// String tweetId = features[2].trim();
line = features[msgColumn].trim();
line = StringUtils.stripAccents(line);
String messages[] = line.split("\\|\\|\\|") ;
String msg = null ;
String prev_msg = null ;
if (messages.length == 2)
{
//context
msg = messages[0] ;
prev_msg = messages[1] ;
// msg = prev_msg + " " + msg ; //no context means commented out
}
else
{
System.out.println(" number of lines are more? " + line) ;
continue ;
}
msg = TextUtility.removeHashtags(msg);
String tokens1[] = tokenizer.tokenize(msg.trim()) ;
prev_msg = TextUtility.removeHashtags(prev_msg);
String tokens2[] = tokenizer.tokenize(prev_msg.trim()) ;
Map<Integer, Double> lexPragFeatMap = null ;
TreeMap<Integer,Double> allFeatures = new TreeMap<Integer,Double>() ;
Map<String,Double> sentiMap1 = sentimentObj.extractSentiFeatures(Arrays.asList(tokens1));
Map<String,Double> sentiMap2 = sentimentObj.extractSentiFeatures(Arrays.asList(tokens2));
// if (! sentiMap1.isEmpty())
{
// if ( label == "1" )
{
String ret = label + "\t" + TextUtility.getValuesOfMap(sentiMap1);//,sentiMap2) ;
writer.write(ret);// + " " + "#" + label + "-" + tweetId );
writer.newLine();
}
// lexPragFeatMap = sarcasmRLObject.createNonNgramFeatures(sentiMap1) ;
// allFeatures.putAll(lexPragFeatMap);
}
// writer.write(label + "\t" + lexPragFeatMap.toString());// + " " + "#" + label + "-" + tweetId );
// writer.newLine();
if ((lineNumber % 100) == 0)
{
// System.out.println("Sentences done " + lineNumber);
}
lineNumber++;
}
writer.close();
System.out.println("Sentences done " + (lineNumber));
}
public void createContextFeatures ( String inputPath, String outputPath, String trainingFile,
EXPERIMENT_MODE experMode, FEATURE_TYPE featType, int context)
throws IOException, ClassNotFoundException
{
TextUtility.loadHashtags();
@SuppressWarnings("resource")
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(inputPath + "/" + trainingFile), "UTF8"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputPath + "/" + trainingFile + ".current.svm."
+ experMode.toString() + "." + "txt"),
"UTF8"));
System.out.println("PROCESSING: " + trainingFile) ;
int lineNumber = 1;
allFeatureMap = new HashMap<String,List<Map<Integer,Double>>>() ;
model = new TokenizerModel(nlpStream);
tokenizer = new TokenizerME(model);
Set<String> uniques = new HashSet<String>() ;
while (true)
{
String line = reader.readLine();
if (null == line)
{
break;
}
// if ( lineNumber == 435)
// {
// System.out.println("here") ;
//}
//check if the format is sgml or not
if(fileFormat.equalsIgnoreCase(FILE_FORMAT.SGML.toString()))
{
//we need to "parse" the line
//first check if the lines contain and preamble or postambles
if(line.contains("<TEXT>") || line.contains("</TEXT>") || line.contains("</DOC>") ||
line.contains("<DOC>"))
{
continue ;
}
//else use the reg expr
line = getXMLCleanText(line) ;
}
String features[] = line.split("\t") ;
String label = features[labelColumn];//getLabel(trainingFile);
label = convert(label) ;
// String target = features[1].trim();
// String tweetId = features[2].trim();
line = features[msgColumn].trim();
line = StringUtils.stripAccents(line);
String messages[] = line.split("\\|\\|\\|") ;
String msg = null ;
String prev_msg = null ;
if (messages.length == 2)
{
//context
msg = messages[0] ;
prev_msg = messages[1] ;
}
else if (messages.length == 1)
{
msg = messages[0] ;
System.out.println ("msg length is 1 - check ") ;
continue ; //we are only dealing where we have the previous context....
}
else
{
System.out.println(" number of lines are more? " + line) ;
continue ;
}
msg = TextUtility.removeHashtags(msg);
prev_msg = TextUtility.removeHashtags(prev_msg);
String tokens1[] = tokenizer.tokenize(msg.trim()) ;
String tokens2[] = tokenizer.tokenize(prev_msg.trim()) ;
context = 0 ;
String tokens_all[] = null ;
String all_msg = null ;
if ( context == 1) //that is both!
{
all_msg = msg + " " + prev_msg ;
tokens_all = tokenizer.tokenize(all_msg.trim()) ;
}
//this is only for the current wsd experiment
List<String> hashes = new ArrayList<String>() ;
Map<Integer, Double> puncFeatMap = null ;
Map<Integer, Double> bowFeatMap = null ;
Map<Integer, Double> lexPragFeatMap = null ;
TreeMap<Integer,Double> allFeatures = new TreeMap<Integer,Double>() ;
if(approvedFeatList.contains(FEATURE_SET.PERIODS.toString()) )
{
Map<String,Double> puncMap = punctFeatureObj.getPuncFVs(msg);
if (!puncMap.isEmpty() )
{
puncFeatMap = sarcasmRLObject.createNonNgramFeatures(puncMap) ;
allFeatures.putAll(puncFeatMap) ;
}
}
if(approvedFeatList.contains(FEATURE_SET.BOW.toString() ) )
{
bowFeatMap = bowFeatureObj.loadFeatures(tokens1);
allFeatures.putAll(bowFeatMap);
}
if(approvedFeatList.contains(FEATURE_SET.WP.toString() ) )
{
bowFeatMap = bowFeatureObj.generateBigrams(tokens1);
allFeatures.putAll(bowFeatMap);
}
if(approvedFeatList.contains(FEATURE_SET.LIWC.toString()) )
{
Map<String,Double> lexPragMap = lexFeatureObj.loadNonLexFeatures(tokens1);
if (! lexPragMap.isEmpty())
{
lexPragFeatMap = sarcasmRLObject.createNonNgramFeatures(lexPragMap) ;
allFeatures.putAll(lexPragFeatMap);
}
}
if(approvedFeatList.contains(FEATURE_SET.SENT.toString()) )
{
Map<String,Double> sentiMap = null ;
Map<String,Double> lexPragMap = null ;
if ( context == 1 )
{
sentiMap = sentimentObj.extractSentiFeatures(Arrays.asList(tokens1),Arrays.asList(tokens2));
lexPragMap = TextUtility.extractSentiFeaturesAsMap(sentiMap,context);
}
else if ( context == 0 )
{
sentiMap = sentimentObj.extractSentiFeatures(Arrays.asList(tokens1));
lexPragMap = TextUtility.extractSentiFeaturesAsMap(sentiMap,context);
}
else
{
System.out.println("error in context setting?") ;
}
if (! lexPragMap.isEmpty())
{
lexPragFeatMap = sarcasmRLObject.createNonNgramFeatures(lexPragMap) ;
allFeatures.putAll(lexPragFeatMap);
}
}
String fv = createFV(allFeatures,featType);
writer.write(label + "\t" + fv);// + " " + "#" + label + "-" + tweetId );
writer.newLine();
if ((lineNumber % 100) == 0)
{
System.out.println("Sentences done " + lineNumber);
}
// if ( lineNumber == 200)
// {
// break ;
// }
lineNumber++;
}
writer.close();
System.out.println("Sentences done " + (lineNumber));
//for training purpose - we write the non unigram file
//update - no we don't write because non-unigram can be used as a
//constant file
//we rather write the bow file? so that feature_weight_calculation
//becomes easier?
if(experMode.equals(EXPERIMENT_MODE.TRAINING))
{
// sarcasmRLObject.writeNonNgramFiles() ;
// sarcasmRLObject.writeNGramFile();
}
if(writingType.equals("weka") )
{
//write a weka file
wekaWriterObj = new WekaWriter();
List<String> nonLexFeatures = sarcasmRLObject.getNonLexFeatures();
List<String> lexFeatures = sarcasmRLObject.getLexFeatures();
List<String> allFeatures = new ArrayList<String>() ;
allFeatures.addAll(lexFeatures);
allFeatures.addAll(nonLexFeatures);
wekaWriterObj.setFeatures(allFeatures);
wekaWriterObj.setStartingPointForFeaturePostion(lexFeatures.size());
wekaWriterObj.setLabels(allFeatureMap.keySet());
wekaWriterObj.setFeatureMap(allFeatureMap);
wekaWriterObj.writeWekaArffFile(wekaPath, trainingFile +".weka") ;
}
//maintain a global map for feature - value type where the value is meaningless
///basically we want to keep an index of all the *features* so that during training
//we can get back to feature indexing by checking which feature is which index
//and what is the value of the feature during training
//this is just for testing and will be removed in production
// String specialFile = "unigram.checkIndex.lst" ;
// bowFeatureObj.close(specialFile) ;
}
public void createFeatures ( String inputPath, String outputPath, String trainingFile,
EXPERIMENT_MODE experMode, FEATURE_TYPE featType)
throws IOException, ClassNotFoundException
{
TextUtility.loadHashtags();
// TextUtility.loadCrimeHashtags();
@SuppressWarnings("resource")
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(inputPath + "/" + trainingFile), "UTF8"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputPath + "/" + trainingFile + ".binary.svm."
+ experMode.toString() + "." + "txt"),
"UTF8"));
System.out.println("PROCESSING: " + trainingFile) ;
int lineNumber = 1;
allFeatureMap = new HashMap<String,List<Map<Integer,Double>>>() ;
model = new TokenizerModel(nlpStream);
tokenizer = new TokenizerME(model);
Set<String> uniques = new HashSet<String>() ;
while (true)
{
String line = reader.readLine();
if (null == line)
{
break;
}
//check if the format is sgml or not
if(fileFormat.equalsIgnoreCase(FILE_FORMAT.SGML.toString()))
{
//we need to "parse" the line
//first check if the lines contain and preamble or postambles
if(line.contains("<TEXT>") || line.contains("</TEXT>") || line.contains("</DOC>") ||
line.contains("<DOC>"))
{
continue ;
}
//else use the reg expr
line = getXMLCleanText(line) ;
}
//sarthak-s data
/*
String features[] = line.split("\\s") ;
String label = features[0].trim();
line = TextUtility.recreate(features,1,features.length);
String tokens[] = line.trim().split("\\s++");
*/
// System.out.println(line);
String features[] = line.split("\t") ;
if ( features.length <2)
{
continue ;
}
String label = features[labelColumn];//getLabel(trainingFile);
label = convert(label) ;
// String target = features[1].trim();
// String tweetId = features[2].trim();
line = features[msgColumn].trim();
line = StringUtils.stripAccents(line);
// line = line.toLowerCase();
//we have some issues in tokenization
//the easy solve is to replace alll hashtags
//if the line contains both hashtags - remove that!
line = TextUtility.removeHashtags(line);
/*
if(uniques.contains(line))
{
continue ;
}
uniques.add(line) ;
*/
String tokens[] = tokenizer.tokenize(line.trim()) ;
// String tokens[] = line.split("\\s++");
//check if sarcasm or sarcastic tokens are part of the text
// boolean presence = TextUtility.checkSarcasm(tokens);
// if(presence)
// {
// continue ;
// }
//this is only for the current wsd experiment
List<String> hashes = new ArrayList<String>() ;
//for all targets
// loadAllHashes(hashes);
// bowFeatureObj.addDataToHashList(hashes) ;
Map<Integer, Double> puncFeatMap = null ;
Map<Integer, Double> bowFeatMap = null ;
Map<Integer, Double> lexPragFeatMap = null ;
TreeMap<Integer,Double> allFeatures = new TreeMap<Integer,Double>() ;
if(approvedFeatList.contains(FEATURE_SET.PERIODS.toString()) )
{
Map<String,Double> puncMap = punctFeatureObj.getPuncFVs(line);
if (!puncMap.isEmpty() )
{
puncFeatMap = sarcasmRLObject.createNonNgramFeatures(puncMap) ;
allFeatures.putAll(puncFeatMap) ;
}
}
if(approvedFeatList.contains(FEATURE_SET.BOW.toString() ) )
{
bowFeatMap = bowFeatureObj.loadFeatures(tokens);
allFeatures.putAll(bowFeatMap);
}
if(approvedFeatList.contains(FEATURE_SET.WP.toString() ) )
{
bowFeatMap = bowFeatureObj.generateBigrams(tokens);
allFeatures.putAll(bowFeatMap);
}
if(approvedFeatList.contains(FEATURE_SET.LIWC.toString()) )
{
Map<String,Double> lexPragMap = lexFeatureObj.loadNonLexFeatures(tokens);
if (! lexPragMap.isEmpty())
{
lexPragFeatMap = sarcasmRLObject.createNonNgramFeatures(lexPragMap) ;
allFeatures.putAll(lexPragFeatMap);
}
}
//we will introduce a feature based on emoticons - but first check the
//training data to see the variations of the such emoticons
//get upper cases (e.g. NEVER) / weird spelling of words (e.g. Coooool/)
// Map<Integer, Integer> bigramMap = bowFeatureObj.generateBigram(tokens);
// create the feature vector
//dummy value at position 1
// allFeatures.put(0, 1);
// allFeatures.putAll(bigramMap);
String fv = createFV(allFeatures,featType);
/*
List<Map<Integer, Double>> fvs = allFeatureMap.get(label);
if ( null == fvs )
{
fvs = new ArrayList<Map<Integer,Double>>();
}
label = convert(label);
fvs.add(allFeatures);
allFeatureMap.put(label, fvs);
*/
if (label.equalsIgnoreCase("pos"))
{
label = "1" ;
}
if (label.equalsIgnoreCase("neg"))
{
label = "0" ;
}
writer.write(label + "\t" + fv);// + " " + "#" + label + "-" + tweetId );
writer.newLine();
if ((lineNumber % 100) == 0)
{
System.out.println("Sentences done " + lineNumber);
}
// if ( lineNumber == 200)
// {
// break ;
// }
lineNumber++;
}
writer.close();
System.out.println("Sentences done " + (lineNumber));
//for training purpose - we write the non unigram file
//update - no we don't write because non-unigram can be used as a
//constant file
//we rather write the bow file? so that feature_weight_calculation
//becomes easier?
if(experMode.equals(EXPERIMENT_MODE.TRAINING) &&
this.unigramTypeEnum == unigramTypeEnum.LOCAL)
{
// sarcasmRLObject.writeNonNgramFiles() ;
//if the ngram is local type we need to write the output for testing...
if(approvedFeatList.contains(FEATURE_SET.BOW.toString()) )
{
sarcasmRLObject.writeUnigramFile();
}
}
if(writingType.equals("weka") )
{
//write a weka file
wekaWriterObj = new WekaWriter();
List<String> nonLexFeatures = sarcasmRLObject.getNonLexFeatures();
List<String> lexFeatures = sarcasmRLObject.getLexFeatures();
List<String> allFeatures = new ArrayList<String>() ;
allFeatures.addAll(lexFeatures);
allFeatures.addAll(nonLexFeatures);
wekaWriterObj.setFeatures(allFeatures);
wekaWriterObj.setStartingPointForFeaturePostion(lexFeatures.size());
wekaWriterObj.setLabels(allFeatureMap.keySet());
wekaWriterObj.setFeatureMap(allFeatureMap);
wekaWriterObj.writeWekaArffFile(wekaPath, trainingFile +".weka") ;
}
//maintain a global map for feature - value type where the value is meaningless
///basically we want to keep an index of all the *features* so that during training
//we can get back to feature indexing by checking which feature is which index
//and what is the value of the feature during training
//this is just for testing and will be removed in production
// String specialFile = "unigram.checkIndex.lst" ;
// bowFeatureObj.close(specialFile) ;
}
private void loadAllHashes(List<String> hashes) throws IOException
{
// TODO Auto-generated method stub
String data = "./data/config/";
String file = "topnames.txt" ;
List<String> targets = Files.readAllLines( Paths.get(data+file), StandardCharsets.UTF_8) ;
for ( String target : targets )
{
hashes.add(target);
hashes.add("#" +target);
}
}
private String convert(String label)
{
// TODO Auto-generated method stub
label = label.trim();
if ( positiveCat.contains(label))
{
return POSITIVE_CAT ;
}
else if ( negativeCat.contains(label))
{
return NEGATIVE_CAT ;
}
else
{
System.out.println("wrong label. check") ;
}
return null;
}
private static String labelConvert(String label)
{
// TODO Auto-generated method stub
if ( label.equalsIgnoreCase("yes"))
return "1" ;
else if ( label.equalsIgnoreCase("no"))
return "2" ;
return null;
}
private String createFV ( Map<Integer,Double> fvs, FEATURE_TYPE type )
{
StringBuffer ret = new StringBuffer();
for ( Integer feature : fvs.keySet() )
{
ret.append(feature);
ret.append(":") ;
if(type.equals(FEATURE_TYPE.BINARY))
{
ret.append("1") ;
}
else if (type.equals(FEATURE_TYPE.COUNT))
{
ret.append(fvs.get(feature));
}
ret.append(" ") ;
}
return ret.toString().trim() ;
}
public void setResourceLoaderToTraining(SarcasmResourceLoader resourceObj)
{
}
public void createFeaturesForTesting(String inputPath, String outputPath, String testingFile)
throws ClassNotFoundException, IOException
{
// TODO Auto-generated method stub
createFeatures(inputPath, outputPath,testingFile, EXPERIMENT_MODE.TESTING, FEATURE_TYPE.BINARY) ;
}
public void setResourcePath(String resourcePath) throws IOException
{
lexFeatureObj.setLexPath(resourcePath) ;
}
public void setNonLexFeatureFile(String nonLexFeatureFile,
String unigramPath) throws IOException
{
sarcasmRLObject.setNonLexfile(nonLexFeatureFile);
// if (experMode.equals(EXPERIMENT_MODE.TESTING) )
{
//we load the non-lex features for everythinge because it is constant!
sarcasmRLObject.loadGlobalNonLexFeatures();
}