将不同的 txt 文件单词转换成图形(使用 JUNG 库)

different txt file words into a graph( with JUNG lib)

我正在尝试制作一个图表,它读取一个 txt 文件并将单词放入图表中,但它不能重复(以防文件中有两个相同的单词)

这是我的代码(使用 JUNG API)

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.Stack;
import edu.uci.ics.jung.graph.DirectedSparseGraph;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.graph.util.EdgeType;


public class Main {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        Scanner scan = null;
/*i have a class named 'Palavra' that returns me a string(did that cause // i'll use the class to implement some things at the word) */

        Stack<Palavra> palavras = new Stack<Palavra>(); // pilha para delimitar
                                                        // tamanho do grafo

        // Read txt
        try {
            scan = new Scanner(new File("C:\Users\Auryon.AURYON-PC\Desktop\Aula1\teste.txt"));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


        /*int i = 0;*/
        Graph<Palavra, Relacao> g = new SparseMultigraph<Palavra, Relacao>();

//我创建的最后一个class(将是我的词关系验证)

        Relacao tipo_palavra = new Relacao("connect");

# 问题出在这里

        while (scan.hasNextLine()) {
            String s = scan.next();
            Palavra word = new Palavra(s);
            if (palavras.contains(word)) {
                s = scan.next();
            } else {
                palavras.push(word);
                g.addVertex(word);
            }
            /*
             * if (i > 0) { g.addEdge(tipo_palavra,word,palavras.lastElement());
             * //multiple edges }
                 */
            }

            System.out.println(g);


    System.out.println(palavras.size());

        }
    }

MY NEW UPDATE

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.Stack;
import edu.uci.ics.jung.graph.DirectedSparseGraph;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.graph.util.EdgeType;

public class Main {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        Scanner scan = null;

        Stack<Palavra> palavras = new Stack<Palavra>(); // Graph Size Stack


        // Read txt
        try {
            scan = new Scanner(new File("C:\Users\Auryon.AURYON-PC\Desktop\Aula1\teste.txt"));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }



        Graph<Palavra, Relacao> g = new SparseMultigraph<Palavra, Relacao>();

        Relacao tipo_palavra = new Relacao("connect");

        String s = scan.next();
        Palavra word = new Palavra(s);
        palavras.push(word);
        g.addVertex(word);

        while (scan.hasNextLine()) {
            s = scan.next();
            word = new Palavra(s);
            //THE REAL PROBLEM
            g.addVertex(word);
            g.addEdge(tipo_palavra, word, palavras.lastElement()); 
            palavras.push(word);



        }
        System.out.println(g);
        System.out.println(palavras.size());

    }
}

正如@DivDiff 所说,目前还不完全清楚你的问题是什么,但听起来你希望输入文件中的单词数与你绘制的图形中的顶点数相同已经创建(其中顶点是单词)。

简短的版本是:只要文件中的每个单词只出现一次,这就是正确的。如果 word 不在图表中并且您执行此操作:

boolean result1 = g.addVertex(word);
boolean result2 = g.addVertex(word);

然后 result1 将是 true(图表已修改),result2 将是 false(图表未修改),如 addVertex.

这个约束——顶点必须是唯一的——允许将顶点用作图的内部数据结构的键,更重要的是作为 getNeighbors() 等方法的参数。

更新:您在下面的评论表明您遇到的实际问题是您正在尝试添加具有不同端点的相同边缘。

特别是,您有一个边对象 (tipo_palavra),并且您重复将该边添加到具有不同端点的图形中。这是行不通的:每个边缘对象都必须是唯一的。

如果除了作为连接两个顶点的手段之外,边本身对您没有任何意义,那么您有两个主要选择:

(1) 为每对端点生成一个新的边缘对象,例如,让边缘是一个整数,每次递增:

g.addEdge(i++, word1, word2);

(2) 使用不同的库来表示不需要显式边缘对象的图形,例如 Guava's common.graph library(在 v20 RC1 中可用),特别是图形类型。

这是答案,我的图表也已完成:

 import java.io.FileNotFoundException;
import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Stack;

import javax.swing.JFrame;

import edu.uci.ics.jung.algorithms.layout.TreeLayout;
import edu.uci.ics.jung.algorithms.layout.CircleLayout;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.algorithms.layout.PolarPoint;
import edu.uci.ics.jung.graph.DirectedSparseGraph;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.graph.util.EdgeType;
import edu.uci.ics.jung.visualization.BasicVisualizationServer;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;

public class Main {

    /**
     * 
     * @param args
     * @throws IOException
     * 
     */

    // BEGIN DEEP SEARCH

    Stack<Word> pilha;

    public void buscaProfundidade(Graph<Word, Relacao> g1, Word n0) {
        HashMap<Integer, Word> visitados = new HashMap<Integer, Word>();
        pilha = new Stack<Word>();
        pilha.add(n0);
        while (!pilha.isEmpty()) {
            Word n = pilha.pop();
            marcarVisitado(n, visitados);
            processarNo(n); // print
            Collection<Word> adjacencias = g1.getNeighbors(n); // coleção dos
                                                                // adjacentes do nó
                                                                // atual
            for (Word adjacente : adjacencias) {
                if (!foiVisitado(adjacente, visitados)) {
                    pilha.push(adjacente);
                }
            }
        }
        // RENDERIZA GRAFO
        Layout<Word, Relacao> layout = new CircleLayout<Word, Relacao>(g1);
        layout.setSize(new Dimension(800, 600)); // sets the initial size of the
                                                    // space
        // The BasicVisualizationServer<V,E> is parameterized by the edge types
        BasicVisualizationServer<Word, Relacao> vv = new BasicVisualizationServer<Word, Relacao>(layout);

        vv.setPreferredSize(new Dimension(800, 600)); // Sets the viewing area
                                                        // size
        vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
        vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
        vv.getRenderContext().setLabelOffset(20);

        JFrame frame = new JFrame("WORD INDICATOR");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(vv);
        frame.pack();
        frame.setVisible(true);
    }

    private void processarNo(Word n) {
        System.out.println(n);

    }

    boolean foiVisitado(Word adjacente, HashMap<Integer, Word> visitados) {

        return visitados.containsKey(adjacente.getId());

    }

    private void marcarVisitado(Word n, HashMap<Integer, Word> visitados) {
        visitados.put(n.getId(), n);

    }

    // DEEP SEARCH END
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        Scanner scan = null;

        Stack<Word> words = new Stack<Word>();
        // CRIA GRAFO
        // Read txt

        try {
            scan = new Scanner(
                    new File("C:\Users\Auryon.AURYON-PC\Documents\GitHub\java-works\Graphs_JUNG\teste.txt"));

            // scan = new Scanner(new
            // File("C:\Users\Auryon.AURYON-PC\Desktop\flatWiki.txt"));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        Graph<Word, Relacao> g = new SparseMultigraph<Word, Relacao>();
        int i = 1;
        Relacao word_type = new Relacao("connect");
        String s = scan.next();
        Word word = new Word(i, s, s, s, s);
        words.push(word);
        g.addVertex(word);

        while (scan.hasNextLine()) {
            i++;
            s = scan.next(); // TODO:implementar classes separadas
            /*
             * s2 s3 s4
             */
            word = new Word(i, s, s, s, s);
            g.addVertex(word);
            try {
                word_type = new Relacao("");
                g.addEdge(word_type, words.lastElement(), word, EdgeType.DIRECTED);
                words.push(word);

            } catch (Exception e) {

            }
            ;

            System.out.println(g);
            System.out.println(words.size());
        }

        Main busca = new Main();
        Collection<Word> vertices = g.getVertices();
        Word p = vertices.iterator().next(); // parametro busca
        busca.buscaProfundidade(g, p);

        // TERMINA GRAFO

    }

}