[英]Get,Put key and values from nested hashmap
我想创建一个嵌套的 HashMap,它返回多个文件中术语的频率。 像,
Map<String, Map<String, Integer>> wordToDocumentMap=new HashMap<>();
我已经能够返回某个术语在文件中出现的次数。
Map<String, Integer> map = new HashMap<>();//for frequecy count
String str = "Wikipedia is a free online encyclopedia, created and edited by
volunteers around the world."; //String str suppose a file a.java
// The query string
String query = "edited Wikipedia volunteers";
// Split the given string and the query string on space
String[] strArr = str.split("\\s+");
String[] queryArr = query.split("\\s+");
// Map to hold the frequency of each word of query in the string
Map<String, Integer> map = new HashMap<>();
for (String q : queryArr) {
for (String s : strArr) {
if (q.equals(s)) {
map.put(q, map.getOrDefault(q, 0) + 1);
}
}
}
// Display the map
System.out.println(map);
在我的代码中,它单独计算给定查询的频率。 但我想要 Map 查询词及其文件名的频率。 我在 web 周围搜索了一个解决方案,但发现很难找到适用于我的解决方案。 任何帮助,将不胜感激!
我希望我理解正确。
你想要的是能够读取文件列表和 map 文件名到你在上面的代码中创建的 map。 因此,让我们从您的代码开始,将其转换为 function:
public Map<String, Integer> createFreqMap(String str, String query) {
Map<String, Integer> map = new HashMap<>();//for frequecy count
// The query string
String query = "edited Wikipedia volunteers";
// Split the given string and the query string on space
String[] strArr = str.split("\\s+");
String[] queryArr = query.split("\\s+");
// Map to hold the frequency of each word of query in the string
Map<String, Integer> map = new HashMap<>();
for (String q : queryArr) {
for (String s : strArr) {
if (q.equals(s)) {
map.put(q, map.getOrDefault(q, 0) + 1);
}
}
}
// Display the map
System.out.println(map);
return map;
}
好的,现在你有一个漂亮的 function 从一个字符串和一个查询中生成一个 map
现在您将要设置一个系统以将文件读入字符串。
有很多方法可以做到这一点。 您可以在此处查看适用于不同 java 版本的一些方法: https://stackoverflow.com/a/326440/9789673
让 go 有了这个(假设 >java 11):
String content = Files.readString(path, StandardCharsets.US_ASCII);
其中路径是您想要的文件的路径。
现在我们可以把它们放在一起:
String[] paths = ["this.txt", "that.txt"]
Map<String, Map<String, Integer>> output = new HashMap<>();
String query = "edited Wikipedia volunteers"; //String query = "hello";
for (int i = 0; i < paths.length; i++) {
String content = Files.readString(paths[i], StandardCharsets.US_ASCII);
output.put(paths[i], createFreqMap(content, query);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.