document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1.  
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.Arrays;
  6. import java.util.Collections;
  7. import java.util.List;
  8.  
  9. import LBJ2.parse.Parser;
  10.  
  11. /**
  12.  * Reads documents, given a directory
  13.  */
  14. public class DocumentReader implements Parser {
  15.    
  16.     private final List files;
  17.     private int currentFileId;
  18.    
  19.     public DocumentReader(String directory) {
  20.         File d = new File(directory);
  21.        
  22.         if (!d.exists()) {
  23.             System.err.println(directory + " does not exist!");
  24.             System.exit(-1);
  25.         }
  26.        
  27.         if (!d.isDirectory()) {
  28.             System.err.println(directory + " is not a directory!");
  29.             System.exit(-1);
  30.         }
  31.        
  32.         files = new ArrayList();
  33.         for (File f : d.listFiles()) {
  34.             if (f.isDirectory()) {
  35.                 files.addAll(Arrays.asList(f.listFiles()));
  36.             }
  37.         }
  38.        
  39.         Collections.shuffle(files);
  40.         currentFileId = 0;
  41.     }
  42.    
  43.     public void close() {
  44.     }
  45.    
  46.     /**
  47.     * Notice that this relies on the files having the label in their paths, as in
  48.     *        data/spam/train/[label]/[filename].txt
  49.     */
  50.     public Object next() {
  51.         if (currentFileId < files.size()) {
  52.             File file = files.get(currentFileId++);
  53.             String[] split = file.getPath().split(File.separator);
  54.             String label = split[split.length - 2];
  55.             try {
  56.                 return new Document(file, label);
  57.             } catch (IOException e) {
  58.                 e.printStackTrace();
  59.                 System.exit(-1);
  60.                 return null;
  61.             }
  62.         } else {
  63.             return null;
  64.         }
  65.     }
  66.    
  67.     public void reset() {
  68.         currentFileId = 0;
  69.     }
  70. }
');