【问题标题】:Positional index implementation in JAVAJAVA中的位置索引实现
【发布时间】:2016-03-28 06:04:51
【问题描述】:

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

String[] docs = {"在段落之间放置新的返回值", "houses which 球衣上新”、“7月房屋销售新涨”}

。位置索引将如下所示,其中具有 [ word docID : position fo 文档中的单词。 PS:String Array中的每一个词组都被认为是一个文档

所需的输出 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;
}

【问题讨论】:

    标签: java indexing data-structures lucene indexof


    【解决方案1】:

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

    改变内循环

    for (String token : tokens) {
        ...
    

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

    你会得到这个词的位置 - j

    代替您当前使用的ArrayLists,为了将您需要的所有数据存储在您的PositionalIndex中,我建议使用Map&lt;String,Map&lt;Integer,Integer&gt;,其中外部Map的键是术语( word) 并且值是Map,其键是文档的索引,值是该文档中词条的索引。

    【讨论】:

    • 我正在使用 matrixString 显示如何将 -j 传递给该函数?
    猜你喜欢
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 2013-02-20
    • 1970-01-01
    相关资源
    最近更新 更多