问题描述
我想创建一个嵌套的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);
在我的代码中,它分别计算给定查询的频率。但是我想用它的文件名映射查询词及其频率。我在网上搜索了一个解决方案,但发现很难找到适合我的解决方案。任何帮助将不胜感激!
解决方法
希望我能正确理解你。
您想要的是能够读取文件列表并将文件名映射到您在上面的代码中创建的映射。因此,让我们从您的代码开始,并将其变成一个函数:
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;
}
好的,现在您有了一个漂亮的函数,可以根据字符串和查询来制作地图
现在,您将要设置一个用于将文件读入字符串的系统。
有很多方法可以做到这一点。您可以在此处查看适用于不同Java版本的某些方式:https://stackoverflow.com/a/326440/9789673
让它伴随(假设> java 11):
String content = Files.readString(path,StandardCharsets.US_ASCII);
其中path是所需文件的路径。
现在我们可以将它们放在一起:
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);
}