我有一个包含如下文本的文件:
4 abiogenezele
5 abiogenezelor
6 acefaliile
7 acefaliilor
8 acetonuriile
....
它的格式为 (ID_WORD WORD) 并且有一个近似值。 ~33000 字。
我想输入一个词来找到他的ID。
我试试这段代码。它有效但效率不高。
int ID;
String word = "acefaliile";
String pattern = "(?i)([\\d]+) ("+word+")";
Pattern r = Pattern.compile(pattern);
boolean found = false;
// Read the file
try (BufferedReader br = new BufferedReader(new FileReader("./resources/txt/lemma.txt"))) {
String line;
while ((line = br.readLine()) != null) {
Matcher m = r.matcher(line);
if (m.find( )) {
// m.group(1) is ID
// m.group(2) is WORD
ID = Integer.parseInt(m.group(1));
found=true;
break;
}
}
if(!found) {
ID = 0;
}
}
最佳答案
- 将文件加载到内存中。
- 用空格分隔行(第一个空格,如果'words'可以包含空格)
- 将数据加载到 map(字典)数据结构(Java 中的 HashMap?),其中 word 作为键,id 作为值。
- 在此 map 中进行搜索。
替代方法 - 将这些键/值对放入数组或列表中,对其进行排序,然后使用二分查找。
关于java - 搜索文件的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34186694/