Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

ExtractVocabulary.java 15 KB

You have to be logged in to leave a comment. Sign In
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
  1. /*
  2. * Copyright 2013,2014 BioASQ project: FP7/2007-2013, ICT-2011.4.4(d),
  3. * Intelligent Information Management,
  4. * Targeted Competition Framework grant agreement n° 318652.
  5. * www: http://www.bioasq.org
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. /**
  20. *
  21. * @author Ioannis Partalas
  22. */
  23. package data.PreProcess;
  24. import com.google.gson.stream.JsonReader;
  25. import data.PubMedDocument;
  26. import data.TaskADataParser;
  27. import java.io.BufferedReader;
  28. import java.io.BufferedWriter;
  29. import java.io.FileReader;
  30. import java.io.FileWriter;
  31. import java.io.IOException;
  32. import java.util.HashSet;
  33. import java.util.Iterator;
  34. import java.util.TreeMap;
  35. import java.util.logging.Level;
  36. import java.util.logging.Logger;
  37. import org.tartarus.snowball.SnowballStemmer;
  38. /**
  39. *
  40. * @author alvertos
  41. */
  42. public class ExtractVocabulary {
  43. HashSet vocabulary;
  44. TreeMap uniqueWords;
  45. JsonReader reader;
  46. public ExtractVocabulary()
  47. {
  48. }
  49. public ExtractVocabulary(String datafile) {
  50. vocabulary = new HashSet();
  51. uniqueWords = new TreeMap();
  52. try {
  53. reader = TaskADataParser.streamParser(datafile);
  54. } catch (IOException ex) {
  55. }
  56. }
  57. public void makeVoc(String vocfile,String uniquefile) throws InstantiationException, IllegalAccessException
  58. {
  59. int numofdocs=0;
  60. Class stemClass;
  61. SnowballStemmer stemmer=null;
  62. try {
  63. stemClass = Class.forName("org.tartarus.snowball.ext.englishStemmer");
  64. stemmer = (SnowballStemmer)stemClass.newInstance();
  65. } catch (ClassNotFoundException ex) {
  66. Logger.getLogger(ExtractVocabulary.class.getName()).log(Level.SEVERE, null, ex);
  67. }
  68. try {
  69. while(reader.hasNext()){
  70. PubMedDocument nextDocument = TaskADataParser.getNextDocument(reader);
  71. numofdocs++;
  72. if(numofdocs%100000==0){
  73. System.out.println(numofdocs + " of documents have been processed");
  74. System.out.println("Size of vocabulary: "+vocabulary.size());
  75. }
  76. String absrt = nextDocument.getText();
  77. String words[] = absrt.split("[\\W]+");
  78. //String wordsInLowerCase[] = new String[words.length];
  79. String wordInLowerCase;
  80. for (int k = 0; k < words.length; k++)
  81. {
  82. wordInLowerCase = words[k].toLowerCase();
  83. stemmer.setCurrent(wordInLowerCase);
  84. if (stemmer.stem()) {
  85. wordInLowerCase = stemmer.getCurrent();
  86. }
  87. if(uniqueWords.containsKey(wordInLowerCase))
  88. {Integer freq = (Integer)uniqueWords.get(wordInLowerCase);
  89. uniqueWords.put(wordInLowerCase,freq.intValue()+1);}
  90. else{uniqueWords.put(wordInLowerCase,1);}
  91. vocabulary.add(wordInLowerCase);
  92. }
  93. }
  94. writeVocabularyToFile(vocfile);
  95. writeUniqueWordsToFile(uniquefile);
  96. } catch (Exception ex) {
  97. writeVocabularyToFile(vocfile);
  98. writeUniqueWordsToFile(uniquefile);
  99. }
  100. TaskADataParser.closeReader(reader);
  101. }
  102. /**
  103. * @param vocfile The vocabulary that will be used to vectorize the documents. For each document a term frequency will be
  104. * calculated
  105. * @param namepmidf
  106. * @param pmidintegerf
  107. * @param outfile
  108. * @throws InstantiationException
  109. * @throws IllegalAccessException
  110. */
  111. public void vectorizeDocuments(String vocfile,String namepmidf,String pmidintegerf,String outfile) throws InstantiationException, IllegalAccessException
  112. {
  113. int numofdocs=0;
  114. Class stemClass;
  115. SnowballStemmer stemmer=null;
  116. try {
  117. stemClass = Class.forName("org.tartarus.snowball.ext.englishStemmer");
  118. stemmer = (SnowballStemmer)stemClass.newInstance();
  119. } catch (ClassNotFoundException ex) {
  120. Logger.getLogger(ExtractVocabulary.class.getName()).log(Level.SEVERE, null, ex);
  121. }
  122. TreeMap vocab = loadVocabularyMap(vocfile);
  123. TreeMap namepmid = loadNamePMIDMapping(namepmidf);
  124. TreeMap pmidinteger = loadPMIDIntegerMapping(pmidintegerf);
  125. BufferedWriter bw = null;
  126. try {
  127. bw = new BufferedWriter(new FileWriter(outfile));
  128. while(reader.hasNext()){
  129. TreeMap doc = new TreeMap();
  130. PubMedDocument nextDocument = TaskADataParser.getNextDocument(reader);
  131. numofdocs++;
  132. if(numofdocs%10000==0){
  133. System.out.println(numofdocs + " of documents have been processed");
  134. }
  135. String absrt = nextDocument.getText();
  136. String words[] = absrt.split("[\\W]+");
  137. //String wordsInLowerCase[] = new String[words.length];
  138. String wordInLowerCase;
  139. String[] meshMajor = nextDocument.getMeshMajor();
  140. for (int k = 0; k < words.length; k++)
  141. {
  142. wordInLowerCase = words[k].toLowerCase();
  143. stemmer.setCurrent(wordInLowerCase);
  144. if (stemmer.stem()) {
  145. wordInLowerCase = stemmer.getCurrent();
  146. }
  147. if(vocab.containsKey(wordInLowerCase))
  148. {
  149. if(doc.containsKey(wordInLowerCase))
  150. {
  151. Integer freq = (Integer)doc.get(wordInLowerCase);
  152. doc.put(wordInLowerCase, freq.intValue()+1);
  153. }else{doc.put(wordInLowerCase, 1);}
  154. }
  155. }
  156. // System.out.println("Size of vectorized doc:"+doc.size());
  157. String vector = vectorToString(doc, vocab);
  158. for(int i=0;i<meshMajor.length;i++)
  159. {
  160. String pmid = (String)namepmid.get(meshMajor[i]);
  161. Integer intid = (Integer)pmidinteger.get(pmid);
  162. if(i==0)
  163. bw.write(intid.toString());
  164. else
  165. bw.write(","+intid.toString());
  166. }
  167. bw.write(vector+"\n");
  168. }
  169. bw.close();
  170. } catch (Exception ex) {
  171. try {
  172. bw.close();
  173. } catch (IOException ex1) {
  174. Logger.getLogger(ExtractVocabulary.class.getName()).log(Level.SEVERE, null, ex1);
  175. }
  176. }
  177. TaskADataParser.closeReader(reader);
  178. }
  179. String vectorToString(TreeMap document,TreeMap vocab)
  180. {
  181. String vec = "";
  182. Iterator iter = document.keySet().iterator();
  183. while(iter.hasNext())
  184. {
  185. String word = (String)iter.next();
  186. Integer id = (Integer)vocab.get(word);
  187. Integer freq = (Integer)document.get(word);
  188. vec+=" "+id.intValue()+":"+freq.doubleValue();
  189. }
  190. return vec;
  191. }
  192. public TreeMap loadPMIDIntegerMapping(String mapfile)
  193. {
  194. BufferedReader br = null;
  195. TreeMap mapping = new TreeMap();
  196. try {
  197. br = new BufferedReader(new FileReader(mapfile));
  198. String line;
  199. while((line=br.readLine())!=null){
  200. String nodes[] = line.split("\\s+");
  201. mapping.put(nodes[0],Integer.parseInt(nodes[1]));
  202. }
  203. br.close();
  204. }catch(IOException ex){
  205. }
  206. return mapping;
  207. }
  208. public TreeMap loadNamePMIDMapping(String mapfile)
  209. {
  210. BufferedReader br = null;
  211. TreeMap mapping = new TreeMap();
  212. try {
  213. br = new BufferedReader(new FileReader(mapfile));
  214. String line;
  215. while((line=br.readLine())!=null){
  216. String nodes[] = line.split("=");
  217. mapping.put(nodes[0],nodes[1]);
  218. }
  219. br.close();
  220. }catch(IOException ex){
  221. }
  222. return mapping;
  223. }
  224. private void writeVocabularyToFile(String vocfile) {
  225. BufferedWriter bw = null;
  226. try {
  227. bw = new BufferedWriter(new FileWriter(vocfile));
  228. Iterator iter = this.vocabulary.iterator();
  229. while(iter.hasNext())
  230. {
  231. String word = (String)iter.next();
  232. bw.write(word+"\n");
  233. }
  234. bw.close();
  235. } catch (IOException ex) {
  236. Logger.getLogger(ExtractVocabulary.class.getName()).log(Level.SEVERE, null, ex);
  237. }
  238. }
  239. private void writeUniqueWordsToFile(String uniqueWordsfile) {
  240. BufferedWriter bw = null;
  241. try {
  242. bw = new BufferedWriter(new FileWriter(uniqueWordsfile));
  243. Iterator iter = this.uniqueWords.keySet().iterator();
  244. while(iter.hasNext())
  245. {
  246. String word = (String)iter.next();
  247. Integer freq = (Integer)uniqueWords.get(word);
  248. bw.write(word+" "+freq.intValue()+"\n");
  249. }
  250. bw.close();
  251. } catch (IOException ex) {
  252. Logger.getLogger(ExtractVocabulary.class.getName()).log(Level.SEVERE, null, ex);
  253. }
  254. }
  255. private void removeStopWords(String filestopwords,String vocabularyfile,String outfile){
  256. HashSet stopwords = loadStopWords(filestopwords);
  257. vocabulary = loadVocabulary(vocabularyfile);
  258. HashSet voc_new = new HashSet();
  259. System.out.println("Size of vocabular: "+vocabulary.size());
  260. Iterator iter = vocabulary.iterator();
  261. while(iter.hasNext())
  262. {
  263. String word = (String)iter.next();
  264. if(!stopwords.contains(word))
  265. voc_new.add(word);
  266. }
  267. System.out.println("Size of vocabular after stopword removal: "+voc_new.size());
  268. writeVocabularyToFile(voc_new,outfile);
  269. }
  270. private void removeLowFrequencyWords(String filesfreqs,String vocabularyfile,String outfile,int min_freq){
  271. TreeMap freqsfile = loadDocTermFrequencies(filesfreqs);
  272. vocabulary = loadVocabulary(vocabularyfile);
  273. HashSet voc_new = new HashSet();
  274. System.out.println("Size of vocabular: "+vocabulary.size());
  275. Iterator iter = vocabulary.iterator();
  276. while(iter.hasNext())
  277. {
  278. String word = (String)iter.next();
  279. Integer freq = (Integer)freqsfile.get(word);
  280. if(freq.intValue()>min_freq)
  281. voc_new.add(word);
  282. }
  283. System.out.println("Size of vocabular after low frequency words removal: "+voc_new.size());
  284. writeVocabularyToFile(voc_new,outfile);
  285. }
  286. private HashSet loadStopWords(String filestopwords) {
  287. HashSet list =new HashSet();
  288. try {
  289. BufferedReader br = null;
  290. br = new BufferedReader(new FileReader(filestopwords));
  291. String line=null;
  292. while((line = br.readLine())!=null)
  293. {
  294. list.add(line);
  295. }
  296. } catch (IOException ex) {
  297. }
  298. return list;
  299. }
  300. private HashSet loadVocabulary(String filevoc) {
  301. HashSet list =new HashSet();
  302. try {
  303. BufferedReader br = null;
  304. br = new BufferedReader(new FileReader(filevoc));
  305. String line=null;
  306. while((line = br.readLine())!=null)
  307. {
  308. list.add(line);
  309. }
  310. } catch (IOException ex) {
  311. }
  312. return list;
  313. }
  314. private TreeMap loadVocabularyMap(String filevoc) {
  315. TreeMap list =new TreeMap();
  316. int counter=1;
  317. try {
  318. BufferedReader br = null;
  319. br = new BufferedReader(new FileReader(filevoc));
  320. String line=null;
  321. while((line = br.readLine())!=null)
  322. {
  323. list.put(line,counter++);
  324. }
  325. } catch (IOException ex) {
  326. }
  327. return list;
  328. }
  329. private TreeMap loadDocTermFrequencies(String filefreq){
  330. TreeMap list =new TreeMap();
  331. try {
  332. BufferedReader br = null;
  333. br = new BufferedReader(new FileReader(filefreq));
  334. String line=null;
  335. while((line = br.readLine())!=null)
  336. {
  337. String temp[] = line.split("\\s+");
  338. list.put(temp[0],Integer.parseInt(temp[1]));
  339. }
  340. } catch (IOException ex) {
  341. }
  342. return list;
  343. }
  344. public static void main(String args[])
  345. {
  346. if(args[0].equals("-makeVoc"))
  347. {
  348. ExtractVocabulary evoc = new ExtractVocabulary(args[1]);
  349. try {
  350. evoc.makeVoc(args[2],args[3]);
  351. } catch (InstantiationException ex) {
  352. } catch (IllegalAccessException ex) {
  353. }
  354. }
  355. if(args[0].equals("-stopwords"))
  356. {
  357. ExtractVocabulary evoc = new ExtractVocabulary();
  358. evoc.removeStopWords(args[1], args[2], args[3]);
  359. }
  360. if(args[0].equals("-lowfreq"))
  361. {
  362. ExtractVocabulary evoc = new ExtractVocabulary();
  363. evoc.removeLowFrequencyWords(args[1], args[2], args[3],Integer.parseInt(args[5]));
  364. }
  365. if(args[0].equals("-vectorize"))
  366. {
  367. ExtractVocabulary evoc = new ExtractVocabulary(args[1]);
  368. try {
  369. evoc.vectorizeDocuments(args[2],args[3],args[4],args[5]);
  370. } catch (InstantiationException ex) {
  371. } catch (IllegalAccessException ex) {
  372. }
  373. }
  374. }
  375. private void writeVocabularyToFile(HashSet voc_new, String outfile) {
  376. BufferedWriter bw = null;
  377. try {
  378. bw = new BufferedWriter(new FileWriter(outfile));
  379. Iterator iter = voc_new.iterator();
  380. while(iter.hasNext())
  381. {
  382. String word = (String)iter.next();
  383. bw.write(word+"\n");
  384. }
  385. bw.close();
  386. } catch (IOException ex) {
  387. Logger.getLogger(ExtractVocabulary.class.getName()).log(Level.SEVERE, null, ex);
  388. }
  389. }
  390. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...