java - JAVA中位置索引的实现

标签 java indexing data-structures lucene indexof

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

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

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

所需输出 把 0 : 0 新0:1,1:3,2:2 返回 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 .

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

关于java - JAVA中位置索引的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36256882/

相关文章:

java - 表达式在 f :facet? JSF 中不起作用

python - 快速索引

c++ - 索引文件名及其内容

scala - 将Scala映射转换为列表

c# - 在从头构建的链表上用 C# 实现 IEnumerable<T>

java - 使用 JDBC 连接到安全数据库

java json 转换时出错

sorting - 快速获取 Pandas 数据框中每一列的前k个元素的索引的方法

java - 无法获取 k-ary 树的叶子数

java - 验证签名,验证返回false