JAVA 中的位置索引实现

Positional index implementation in JAVA

我正在使用 Java 创建位置索引,它具有文档 ID 和单词的位置,例如:如果我们有一个包含三个文档的场景,一个文档

String[] docs = {"put new returns between paragraphs", "houses which are new in jersey", "home sales new rise in july"}

。位置索引将如下所示,其中包含 [ word docID : word 在文档中的位置。 PS:字符串数组中的每个短语都被视为一个文档

期望的输出 put 0 : 0 new 0 : 1 , 1 : 3 , 2 : 2 returns 0 : 2 ....

这是我试过的方法,但是我无法获取单词的位置

public static void main(String[] args) {
    String[] docs = { "put new returns between paragraphs", "houses which are new in jersey", "home sales new rise in july"};
    PositionalIndex pi = new PositionalIndex(docs);
    System.out.print(pi);

}

位置指数

public PositionalIndex(String[] docs) {

    ArrayList<Integer> docList;
    docLists = new ArrayList<ArrayList<Integer>>();
    termList = new ArrayList<String>();
    myDocs = docs;

    for (int i = 0; i < myDocs.length; i++) {
        String[] tokens = myDocs[i].split(" ");
        for (String token : tokens) {
            if (!termList.contains(token)) {// a new term
                termList.add(token);
                docList = new ArrayList<Integer>();
                docList.add(new Integer(i));
                System.out.println(docList);
                docLists.add(docList);
            } else {// an existing term

                int index = termList.indexOf(token);
                docList = docLists.get(index);
                if (!docList.contains(new Integer(i))) {
                    docList.add(new Integer(i));
                    docLists.set(index, docList);
                }
            }
        }
    }
}

显示

/**
 * Return the string representation of a positional index
 */
public String toString() {
    String matrixString = new String();
    ArrayList<Integer> docList;
    for (int i = 0; i < termList.size(); i++) {
        matrixString += String.format("%-15s", termList.get(i));
        docList = docLists.get(i);
        for (int j = 0; j < docList.size(); j++) {
            matrixString += docList.get(j) + "\t";
        }
        matrixString += "\n";
    }
    return matrixString;
}

问题是您使用的是增强的 for 循环,它隐藏了索引。

改变内循环

for (String token : tokens) {
    ...

for (int j=0; j<tokens.length;j++) {
    String token = tokens[j];
    ...

你将得到单词的位置 - j

为了在 PositionalIndex 中存储您需要的所有数据,我建议使用 Map<String,Map<Integer,Integer>,而不是您当前使用的 ArrayList,其中outer Map 是术语(单词),值是一个 Map ,其键是文档的索引,值是该文档中的术语索引。