为语料库构建一个简单的索引



所以我正在做这个小项目,为 1400 个文件语料库构建索引,然后使用该索引搜索关键字。 索引应具有关键字的频率及其位置"文件名"。输出应根据每个文档中关键字的频率排在前十个相关文档。

例如: 花文本1.txt 3 花文本2.txt 2 . . 这就是我到目前为止所拥有的,我在使用元组时遇到困难,因为我想在哈希图中添加 3 个值

import java.io.*;
import java.nio.charset.*;
import java.nio.file.*;
import java.util.*;
public class MyIndex {

static Map<String, Tuple<Integer, String>> map = new HashMap();
static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}

public static void main (String [] args) throws IOException {
File myDirectory = new File(
"/Users/.../processedFiles");
File[] fileList = myDirectory.listFiles();
for(int i = 1;i<fileList.length;i++) {
Scanner scan = new Scanner (new File(fileList[i].getPath()));
while(scan.hasNextLine()) {
String line = scan.nextLine();
map.put(line, new Tuple (1,fileList[i].getName())); //tuple is frequency of word and file name
}
}
}
public class Tuple<X, Y> { 
public final X x; 
public final Y y; 
public Tuple(X x, Y y) { 
this.x = x; 
this.y = y; 
} 
} 

}

错误在 put(...

我还没有添加频率方法,这就是我到目前为止所拥有的

static void frequency(String [] array) {
Map<String, Integer> map = new HashMap<String, Integer>();
for (String string : array) {
int count = 0;
if (!map.containsKey(string)) {
map.put(string, 1);
}
else {
count = map.get(string);
map.put(string, count + 1);
}
}

有没有更好的方法从头开始做到这一点,因为我们无法使用 Lucene 等。 如何使用 Tuple 类将它们放在一起以读取和索引 1400 个文件? 我愿意接受任何建议 谢谢

我想在哈希图中添加 3 个值

地图的定义仅为每个字符串存储 1 个元组。我建议让第二个参数是元组的数组列表。(附言Pair 类存在,因此您不必创建元组类(。这将改变您的地图,而不是您所要求的:

花文1.txt 3、花文2.txt 2

花文本1.txt 3,文本2.txt 2

其中键是"花",val 是一个数组列表,位置 0 = 元组(3, text1.txt(,位置 1 = 元组(2, text2.txt(。您可以参考下面的代码。

Arraylist<Tuple> A = map.get("flower")
System.out.println(A.get(0).y + " " + A.get(0).x)
System.out.println(A.get(1).y + " " + A.get(1).x)

我不确定为什么需要您的频率方法,因为您可以在读取文件时更新频率。因为这听起来像是你的任务,所以我不会给你所有的细节,但会为你指出正确的方向:

while(scan.hasNextLine()) {
//Read all the words in the line and update their count in the map while being aware of the name of the file you're currently reading.
}

你仍然需要弄清楚一些事情,但我希望我有所帮助。

最新更新