位置索引在java中的实现

ffx8fchx  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(329)

我正在使用java创建一个位置索引,它有documentid和单词的位置,例如:如果我们有一个场景,其中有三个文档,一个文档
string[]docs={“在段落之间输入新回报”,“新泽西的房子”,“7月房屋销售新增长”}
. 位置索引将具有如下所示的[word docid:文档中单词的位置]。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;
}
eqqqjvef

eqqqjvef1#

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

for (String token : tokens) {
    ...

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

你会知道这个词的位置- j .
而不是 ArrayList 您当前正在使用的,以便将您需要的所有数据存储在 PositionalIndex ,我建议 Map<String,Map<Integer,Integer> ,其中 Map 是术语(词),值是 Map 其键是文档的索引,其值是该文档中术语的索引。

相关问题