Tokenização de palavras em arquivos txt, doc e pdf

9 respostas
M

Pessoal, sou iniciante em Java e estou precisando fazer um trabalho da seguinte forma:

1) Abrir um arquivo txt, doc ou pdf
2) Ler o arquivo fazendo uma tokenização
3) reconhecer os tokens que são apenas palavras (words)
4) imprimir em uma janela de saída estes tokens

Porém, não está funcionando corretamente com o código abaixo. Abre os arquivos sem problemas, mas na exibição das palavras (tokens) acontece o seguinte:

- arquivos "txt" está perfeito!!
- arquivos "doc" aparecem caracteres estranhos, depois os tokens (palavras) corretamente e, em seguida, caracteres estranhos novamente
- arquivos "pdf" só aparecem caracteres estranhos

O problema está na leitura dos textos ou exibição na janela de saída? Como resolvo isto?

Antecipadamente, muito obrigado.

Marcus.

/* 
* ConstrutorDeTemplate1.java 
* 
* Created on 9 de Junho de 2007, 14:54 
* 
* @author 
*/ 

package br.unifacs.dis2007.template1; 

// Java core packages 
import java.awt.*; 
import java.awt.event.*; 
import java.io.*; 
import java.text.*; 
import java.util.*; 

// Java extension packages 
import javax.swing.*; 


public class ConstrutorDeTemplate1 extends JFrame 
implements ActionListener { 

private JTextField enterField; 
private JTextArea outputArea; 
private BufferedWriter out; 
private String word; 

// set up GUI 
public ConstrutorDeTemplate1() 
{ 
super( "Testing class File" ); 

enterField = new JTextField( 
"Enter file or directory name here" ); 
enterField.addActionListener( this ); 
outputArea = new JTextArea(); 

ScrollPane scrollPane = new ScrollPane(); 
scrollPane.add( outputArea ); 

Container container = getContentPane(); 
container.add( enterField, BorderLayout.NORTH ); 
container.add( scrollPane, BorderLayout.CENTER ); 

setSize( 400, 400 ); 
show(); 
} 

// display information about file user specifies 
public void actionPerformed( ActionEvent actionEvent ) 
{ 
File name = new File( actionEvent.getActionCommand() ); 

// if name exists, output information about it 
if ( name.exists() ) { 
outputArea.setText( 
name.getName() + " exists\n" + 
( name.isFile() ? 
"is a file\n" : "is not a file\n" ) + 
( name.isDirectory() ? 
"is a directory\n" : "is not a directory\n" ) + 
( name.isAbsolute() ? "is absolute path\n" : 
"is not absolute path\n" ) + 
"Last modified: " + name.lastModified() + 
"\nLength: " + name.length() + 
"\nPath: " + name.getPath() + 
"\nAbsolute path: " + name.getAbsolutePath() + 
"\nParent: " + name.getParent() ); 

// output information if name is a file 
if ( name.isFile() ) { 

// append contents of file to outputArea 

try { 
// Create the tokenizer to read from a file 
FileReader rd = new FileReader(name); 
StreamTokenizer st = new StreamTokenizer(rd); 

// Prepare the tokenizer for Java-style tokenizing rules 
st.parseNumbers(); 
st.wordChars('_', '_'); 
st.eolIsSignificant(true); 

// If whitespace is not to be discarded, make this call 
st.ordinaryChars(0, ' '); 

// These calls caused comments to be discarded 
st.slashSlashComments(true); 
st.slashStarComments(true); 

// Parse the file 
int token = st.nextToken(); 
String word_ant = ""; 
outputArea.append( " \n" ); 
out = new BufferedWriter(new FileWriter(name, true)); 

while (token != StreamTokenizer.TT_EOF) { 
token = st.nextToken(); 
if (token == StreamTokenizer.TT_EOL){ 
out.flush(); 
out = new BufferedWriter(new FileWriter(name, true)); 
} 

switch (token) { 
case StreamTokenizer.TT_NUMBER: 
// A number was found; the value is in nval 
double num = st.nval; 
break; 
case StreamTokenizer.TT_WORD: 
// A word was found; the value is in sval 

word = st.sval; 

outputArea.append( word.toString() + " \n " ); 

break; 

case '"': 
// A double-quoted string was found; sval contains the contents 
String dquoteVal = st.sval; 
break; 
case '\'': 
// A single-quoted string was found; sval contains the contents 
String squoteVal = st.sval; 
break; 
case StreamTokenizer.TT_EOL: 
// End of line character found 
break; 
case StreamTokenizer.TT_EOF: 
// End of file has been reached 
break; 
default: 
// A regular character was found; the value is the token itself 
char ch = (char)st.ttype; 
break; 
} // fim do switch 
} // fim do while 
rd.close(); 
out.close(); 
} // fim do try 


// process file processing problems 
catch( IOException ioException ) { 
JOptionPane.showMessageDialog( this, 
"FILE ERROR", 
"FILE ERROR", JOptionPane.ERROR_MESSAGE ); 
} 
} // fim do if da linha 68 

// output directory listing 
else if ( name.isDirectory() ) { 
String directory[] = name.list(); 

outputArea.append( "\n\nDirectory contents:\n"); 

for ( int i = 0; i < directory.length; i++ ) 
outputArea.append( directory[ i ] + "\n" ); 
} 
} // fim do if da linha 52 

// not file or directory, output error message 
else { 
JOptionPane.showMessageDialog( this, 
actionEvent.getActionCommand() + " Does Not Exist", 
"ERROR", JOptionPane.ERROR_MESSAGE ); 
} 

} // fim do método actionPerformed 

// executa a aplicação 
public static void main( String args[] ) 
{ 
ConstrutorDeTemplate1 application = new ConstrutorDeTemplate1(); 

application.setDefaultCloseOperation( 
JFrame.EXIT_ON_CLOSE ); 
} // fim do método main 

}

9 Respostas

F

Por favor edite o tópico e utilize a tag CODE para exibir seu código.

Ninguém é obrigado a ler essa “meleca” :stuck_out_tongue:

Vlw

_

Bom, nao li seu codigo inteiro, mas só pelos imports percebi que voce nao usou nenhuma biblioteca de leitura de DOCs e PDFs.

Estes arquivos nao sao como arquivos TXT que contem apenas os textos, eles contem outras informações sobre o texto, como formatação, imagens, posicionamento, etc.

Para ler arquivos DOC, procure sobre a biblioteca POI, da jakarta.

Para ler PDF, existem varias bibliotecas, eu me dei muito bem com a PDFBox.

As duas sao bem faceis de achar via google.

boa sorte!

A

Pra ler dados em PDF, sugiro usar o trial da PDFTextStream

M

Valeu a atenção!!

Vou experimentar e dou um retorno.

M

_Renatu e Aldrin Leal, obrigado pela dica de vcs, mas, como não consegui fazer a tokenização diretamente nos arquivos PDF, resolvi transformar o PDF em TXT e depois executar o processo de tokenização.

Fica mais simples, porque o PDF tem muitas informações (formatação, etc.) além do simples texto.

De qualquer maneira, se vcs tiverem pronto algum exemplo de como fazer diretamente no PDF, gostaria de dar uma olhada para aprender.

Valeu!!

Marcus.

F

Como foi que você conseguiu abrir um arquivo.txt? Você utilizou JFileChooser? Se sim, como foi feito?

Desculpe perguntar ao invés de ajudar, mas é uma coisa que venho tentando fazer mas sem sucesso.

M

FabricioPJ , observe o código que enviei nesta msg. Para arquivo.txt está OK.

Abs,

Marcus.

F

Opa colega, consegui algum progresso. Com o seguinte código, consigo fazer exibir um arquivo .txt em um textArea, porém...

JFileChooser fc = new JFileChooser();
     StringBuffer cont = new StringBuffer();               
     int res = fc.showOpenDialog(null);
                    
              if(res == JFileChooser.APPROVE_OPTION){
                 File arquivo = fc.getSelectedFile();
                 campo.setText("");
                 
                 try {
                    BufferedReader in = new BufferedReader(new FileReader(arquivo));
                    String str, texto = "";
                    while((str = in.readLine()) != null){
                        texto = texto + str;
                        cont.append(str + "\n");
                        str = in.readLine();
                    }
                    campo.setText(texto);
                    in.close();
                 } 
                 catch (IOException ioe){
                   JOptionPane.showMessageDialog(null, "ERRO");
                 }
              }

... o arquivo é exibido em uma linha apenas. Criei um .txt contento a frase "testando, testando" em 10 linhas, mas em minha aplicação, as 10 linhas são exibidas em uma única apenas. Você poderia me ajudar neste pequeno detalhe?

Grato pela ajuda.

R

ola

eu tenho de ler um ficheiro e imprimir

1 ; 96123456 ; John Smith ; Rua de Cima ; 253987654 ; hipertens?o
3 ; 96234567 ; Maria Fatima ; Rua de Baixo ; 253876543 ; hipotens?o
4 ; 96345678 ; Maria Luisa ; Avenida Central ; 253765432 ; RC alto
5 ; 96456789 ; Manuel Luis ; Pra?a Comercio ; 253654321 ; RC baixo

como posso imprimir em linhas separadas o que esta separado de ";"

tenho este codigo ate agora

comprimentos

import java.io.*;      
      
   public class Dados{      
   public static void main(String[] args){      
   try {      
   BufferedReader in = new BufferedReader(new FileReader("conteudo.txt"));      
   String str;      
   while((str = in.readLine()) != null)      
   {      
   if(str.startsWith("#"))      
   {      
   str= "";      
   }      
   else{      
      
      
   System.out.println(str);      
   }      
   }      
   in.close();      
   }      
   catch (IOException e){      
   // possiveis erros são tratatos aqui      
   }      
      
   System.exit(0);      
   }      
   }
Criado 25 de julho de 2007
Ultima resposta 6 de jun. de 2011
Respostas 9
Participantes 6