簡體   English   中英

從嵌套的 hashmap 中獲取、放置鍵和值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM