java.lang.NullPointerException输出项频率 - 逆文档频率(tfidf)矩阵java

时间:2014-04-07 06:52:26

标签: java file matrix hashmap tf-idf

我有这段代码,为目录中每个文件中的所有单词输出tfidf。我正在尝试将其传输到矩阵,其中每行对应于目录中的每个文件,每列对应于文件中的所有单词,我有一些困难,我需要一些帮助。 我得到的是当我尝试输出矩阵时的java.lang.NullPointerException。 值开始出现但由于某种原因它们会停止并产生null错误。

这是代码

public class TestTF_IDF {

public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException{
    //Test code for TfIdf
    TfIdf tf = new TfIdf("E:/Thesis/ThesisWork/data1");
    //Contains file name being processed
    //String file;


    tf.buildAllDocuments();


    int numDocuments = tf.documents.size();
    Double matrix[][] = new Double[numDocuments][];

    int documentIndex = 0;
    for (String file : tf.documents.keySet())
    {
       // System.out.println("File \t" + file);

        Map<String, Double[]> myMap = 
            tf.documents.get(file).getF_TF_TFIDF();

        int numWords = myMap.size();
        matrix[documentIndex] = new Double[numWords];

        int wordIndex = 0;
        for (String key : myMap.keySet())
        {
            Double[] values = myMap.get(key);
            matrix[documentIndex][wordIndex] = values[2];
            wordIndex++;
             //System.out.print("file="+ file+ "term=" +key + values[2]+" ");
        }
        documentIndex++;


        for(int i=0; i<numDocuments;i++){
            for(int j=0; j<numWords;j++){

           System.out.print("file="+ file+ matrix[i][j]+ " ");  //error here
            }
        }
    }

}//public static void main(String[] args)
 }//public class TestTF_IDF

任何想法。感谢

1 个答案:

答案 0 :(得分:1)

虽然问题非常明显,但我根据问题和评论试图猜测。

import java.util.Map;

public class TestTF_IDF
{
    public static void main(String[] args) throws Exception
    {
        TfIdf tf = new TfIdf("E:/Thesis/ThesisWork/data1");
        tf.buildAllDocuments();

        int numDocuments = tf.documents.size();
        Double[] matrix[][] = new Double[numDocuments][][];

        int documentIndex = 0;
        for (String file : tf.documents.keySet())
        {
            System.out.println("File \t" + file);

            Map<String, Double[]> myMap = 
                tf.documents.get(file).getF_TF_TFIDF();

            int numWords = myMap.size();
            matrix[documentIndex] = new Double[numWords][];

            int wordIndex = 0;
            for (String key : myMap.keySet())
            {
                Double[] values = myMap.get(key);
                matrix[documentIndex][wordIndex] = values;
                wordIndex++;
            }
            documentIndex++;
        }
    }
} 


class Document
{
    public Map<String, Double[]> getF_TF_TFIDF()
    {
        return null;
    }
}

class TfIdf
{
    public Map<String, Document> documents;
    TfIdf(String s)
    {
    }
    public void buildAllDocuments()
    {
    }
}
相关问题