如何确定每个文档中术语的术语频率?

时间:2011-04-15 12:47:10

标签: java frequency

我正在构建倒排索引,但在检查数据库时,我似乎无法获得正确的频率。我到处读到你应该使用HashMap,但我不确定这是否是正确的方法。有什么想法吗?

public class Tokenize {

public static void createIndex() throws Exception{

    ArrayList<Dokument> dok = new QueryHandler().getDokuments();
    ArrayList<String> queries = new ArrayList<String>();
    ArrayList<String> queries2 = new ArrayList<String>();
    HashMap<String, Integer> frek = new HashMap<String, Integer>();

    for(int d = 0; d < dok.size(); d++){
        String token = "";
        int frekvens = 0;


        try{

            Dokument document = dok.get(d);
            StringTokenizer st = new StringTokenizer(document.dokument());
            while (st.hasMoreTokens()) {


                token = st.nextToken();
                token.replaceAll("[']", "");
                token.replaceAll("[,]", "");
                token.replaceAll("[)]", "");
                token.replaceAll("[(]", "");
                token.replaceAll("[.]", "");
                frekvens ++;
                frek.put(token, frekvens);


                    queries.add("INSERT IGNORE INTO termindeks (docID, term) values ("+document.docID()+", '"+token+"')");
                    queries2.add("INSERT IGNORE INTO invertedindeks (term, docID, termfrekvens) values ('"+token+"', "+document.docID()+", "+ frekvens+")");


            }
        }


        catch (Exception e) {
        e.printStackTrace();
        System.out.println(token);
        }
    }

    String[] ffs = new String[queries.size()];
    ffs = queries.toArray(ffs);
    getDB().runQueriesIgnoreException(queries.toArray(ffs));

    String[] ffs2 = new String[queries2.size()];
    ffs2 = queries2.toArray(ffs2);
    getDB().runQueriesIgnoreException(queries2.toArray(ffs2));

}

}

2 个答案:

答案 0 :(得分:2)

您应首先获取令牌的值,递增并再次放置。

在你的循环中这样:

Integer frekvens = frek.get(token); //remove the other frekvens as it's not needed - or find a better name for this one ;)
if( frekvens == null ) { frekvens = 0 };
frekvens++;
frek.put(token, frekvens);

答案 1 :(得分:1)

这个想法是正确的,但据我所知,你没有正确使用HashMap。您必须获得与密钥关联的值,即

Integer i = map.get(token);
i += 1;
map.put(token, i);

修改

另一种选择是使用AtomicInteger代替Integer,因为AtomicInteger是可变的。

Map<String, AtomicInteger> map = new HashMap<String, AtomicInteger>();    
map.get(token).getAndIncrement();