我正在使用 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/