2015-08-13 1 views
1

** Я хочу найти буквенно-цифровой текст (номер счета F0000004511) из документа PDF с использованием регулярного выражения из Java. как я могу добиться этого? например, первая страница PDF такова:Как получить регулярный поиск буквенно-цифрового текста в PDF-документе с использованием java Apache Lucene?

Продажи - Счет-фактура T.I.N. № 02020600021 Номер факса + 91-1792-232268 Номер счета-фактуры F0000004511

В PDF-счете второй страницы нет изменений в F0000004512 и третьей и четвертой странице с таким же номером. Мне нужен поиск и разбивка страницы в формате pdf в соответствии с номером счета-фактуры. Я использую APACHE LUCENE 3.4.0 для индексирования и поиска pdf. ниже код для индексации PDF **

public class Indexer { 

    private final String sourceFilePath = "G:/PDFCopy"; //give the location of the source files location here 
    private final String indexFilePath = "G:/searchEngine"; //give the location where you guys want to create index 
    private IndexWriter writer = null; 
    private File indexDirectory = null; 
    private String fileContent; //temp storer of all the text parsed from doc and pdf 


    private Indexer() throws FileNotFoundException, CorruptIndexException, IOException { 
     try { 
      long start = System.currentTimeMillis(); 
      createIndexWriter(); 
      checkFileValidity(); 
      closeIndexWriter(); 
      long end = System.currentTimeMillis(); 
      System.out.println("Total Document Indexed : " + TotalDocumentsIndexed()); 
      System.out.println("Total time" + (end - start)/(100 * 60)); 
     } catch (Exception e) { 
      System.out.println("Sorry task cannot be completed"); 
     } 
    } 


    private void createIndexWriter() { 
     try { 
      indexDirectory = new File(indexFilePath); 
      if (!indexDirectory.exists()) { 
       indexDirectory.mkdir(); 
      } 
      FSDirectory dir = FSDirectory.open(indexDirectory); 
      StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_34); 
      IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_34, analyzer); 
      writer = new IndexWriter(dir, config); 
     } catch (Exception ex) { 
      System.out.println("Sorry cannot get the index writer"); 
     } 
    } 


    private void checkFileValidity() { 

     File[] filesToIndex = new File[100]; // suppose there are 100 files at max 
     filesToIndex = new File(sourceFilePath).listFiles(); 
     for (File file : filesToIndex) { 
      try { 
       //to check whenther the file is a readable file or not. 
       if (!file.isDirectory() 
         && !file.isHidden() 
         && file.exists() 
         && file.canRead() 
         && file.length() > 0.0 
         && file.isFile()) { 
        if(file.getName().endsWith(".txt")){ 
         indexTextFiles(file);//if the file text file no need to parse text. 
        System.out.println("INDEXED FILE " + file.getAbsolutePath() + " :-) "); 
        } 
        else if(file.getName().endsWith(".doc") || file.getName().endsWith(".pdf")){ 
         //different methof for indexing doc and pdf file. 
         StartIndex(file);      
        } 
       } 
      } catch (Exception e) { 
       System.out.println("Sorry cannot index " + file.getAbsolutePath()); 
      } 
     } 
    } 



    public void StartIndex(File file) throws FileNotFoundException, CorruptIndexException, IOException { 
     fileContent = null; 
     try { 
      Document doc = new Document(); 
      if (file.getName().endsWith(".doc")) { 
       //call the doc file parser and get the content of doc file in txt format 
       fileContent = new DocFileParser().DocFileContentParser(file.getAbsolutePath()); 
      } 
      if (file.getName().endsWith(".pdf")) { 
       //call the pdf file parser and get the content of pdf file in txt format 
       fileContent = new PdfFileParser().PdfFileParser(file.getAbsolutePath()); 
      } 
      doc.add(new Field("content", fileContent, 
        Field.Store.YES, Field.Index.ANALYZED, 
        Field.TermVector.WITH_POSITIONS_OFFSETS)); 
      doc.add(new Field("filename", file.getName(), 
        Field.Store.YES, Field.Index.ANALYZED)); 
      doc.add(new Field("fullpath", file.getAbsolutePath(), 
        Field.Store.YES, Field.Index.ANALYZED)); 
      if (doc != null) { 
       writer.addDocument(doc); 
      } 
      System.out.println("Indexed" + file.getAbsolutePath()); 
     } catch (Exception e) { 
      System.out.println("error in indexing" + (file.getAbsolutePath())); 
     } 
    } 


    private void indexTextFiles(File file) throws CorruptIndexException, IOException { 
     Document doc = new Document(); 
     doc.add(new Field("content", new FileReader(file))); 
     doc.add(new Field("filename", file.getName(), 
       Field.Store.YES, Field.Index.ANALYZED)); 
     doc.add(new Field("fullpath", file.getAbsolutePath(), 
       Field.Store.YES, Field.Index.ANALYZED)); 
     if (doc != null) { 
      writer.addDocument(doc); 
     } 
    } 


    private int TotalDocumentsIndexed() { 
     try { 
      IndexReader reader = IndexReader.open(FSDirectory.open(indexDirectory)); 
      return reader.maxDoc(); 
     } catch (Exception ex) { 
      System.out.println("Sorry no index found"); 
     } 
     return 0; 
    } 


    private void closeIndexWriter() { 
     try { 
      writer.optimize(); 
      writer.close(); 
     } catch (Exception e) { 
      System.out.println("Indexer Cannot be closed"); 
     } 
    } 

    public static void main(String arg[]) { 
     try { 
      new Indexer(); 
     } catch (Exception ex) { 
      System.out.println("Cannot Start :("); 
     } 
    } 
} 

ниже код для поиска в индексе. здесь я непосредственно просматриваю регулярное выражение. но можно ли выполнять поиск с использованием значений регулярных выражений во всех PDF-файлах и читать счет-фактуру. Наконец, мне нужно разделить PDF в соответствии со счетом № . Мне нужно вернуть счет-фактуру без значения из регулярного выражения и разделить tht pdf. (Источник PDF есть 60 страниц с уникальным и повторного счета-фактуры п)

public class Searcher { 

    public Searcher(String searchString) { 
     try { 
      IndexSearcher searcher = new IndexSearcher(FSDirectory.open(
        new File("G:/searchEngine"))); 
      Analyzer analyzer1 = new StandardAnalyzer(Version.LUCENE_34); 
      QueryParser queryParser = new QueryParser(Version.LUCENE_34, "content", analyzer1); 
      QueryParser queryParserfilename = new QueryParser(Version.LUCENE_34, "fullpath", analyzer1); 
      Query query = queryParser.parse(searchString);//to search in the content 
      Query queryfilename = queryParserfilename.parse(searchString);//to search the file name only   
      TopDocs hits = searcher.search(query, 10000); //for 
      ScoreDoc[] document = hits.scoreDocs; 
      System.out.println("Total no of hits for content: " + hits.totalHits); 


      for (int i = 0; i < document.length; i++) { 
       Document doc = searcher.doc(document[i].doc); 
       String filePath = doc.get("fullpath"); 
       System.out.println(filePath); 
      } 


     } catch (Exception e) { 
     } 

    } 

    public static void main(String args[]) 
    { 
     new Searcher("Invoice No.\\s\\w\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d"); 
    } 
} 
+0

Возможно, вы используете QueryParser для генерации ваших запросов в Lucene версии 3.4. Поддержка Regex не была добавлена ​​в QueryParser, пока, я считаю, версия 4.0. Чтобы выполнить поиск с помощью регулярного выражения, вам необходимо вручную создать [RegexQuery] (http://lucene.apache.org/core/3_4_0/api/contrib-queries/org/apache/lucene/search/regex/RegexQuery.html). – femtoRgon

ответ

0

Решение, предложенное femtoRgon:

Ну, по всей видимости, с помощью QueryParser для генерации запросов в Lucene версии 3.4 , Поддержка Regex не была добавлена ​​в QueryParser, пока, я считаю, версия 4.0. Чтобы выполнить поиск с помощью регулярного выражения, вам нужно вручную создать RegexQuery.

Смежные вопросы