【发布时间】:2020-08-16 14:57:56
【问题描述】:
我想从名为 a.java 的文件中搜索查询。如果我的查询是字符串名称,我想从文本文件的查询中单独获取字符串的频率。首先,我必须计算字符串的频率,然后单独命名,然后将频率都添加。如何在java平台上实现这个程序?
public class Tf2 {
Integer k;
int totalword = 0;
int totalfile, containwordfile = 0;
Map<String, Integer> documentToCount = new HashMap<>();
File file = new File("H:/java");
File[] files = file.listFiles();
public void Count(String word) {
File[] files = file.listFiles();
Integer count = 0;
for (File f : files) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(f));
count = documentToCount.get(word);
documentToCount.clear();
String line;
while ((line = br.readLine()) != null) {
String term[] = line.trim().replaceAll("[^a-zA-Z0-9 ]", " ").toLowerCase().split(" ");
for (String terms : term) {
totalword++;
if (count == null) {
count = 0;
}
if (documentToCount.containsKey(word)) {
count = documentToCount.get(word);
documentToCount.put(terms, count + 1);
} else {
documentToCount.put(terms, 1);
}
}
}
k = documentToCount.get(word);
if (documentToCount.get(word) != null) {
containwordfile++;
System.out.println("" + k);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} public static void main(String[] args) throws IOException {Tf2 ob = new Tf2();String query="String name";ob.Count(query);
}}
我用 hashmap 试过这个。但它不能单独统计查询的频率。
【问题讨论】:
-
你能提供一个示例文本和预期结果吗?
-
@aeberhart 好的,我会向你澄清。如果我有一个包含一行的文件,请点击此处维基百科是免费的在线百科全书,由世界各地的志愿者创建和编辑.我想搜索一个查询edited Wikipedia志愿者。然后我的程序首先计算从文本文件中编辑的频率,然后计算维基百科频率,然后是志愿者频率,最后总结所有频率。可以用 hashmap 解决吗?
-
您希望对同一文本进行多少次查询?如果会有多个查询,那么您可以相应地进行优化。如果有一个查询,那么最好的选择是将查询的单词放入一个集合中,然后逐个遍历实际单词。因此复杂度将是 O(n + k),其中 n 是文本中的单词数。而 k 是查询中的单词数
标签: java algorithm file hashmap tf-idf