亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何查找數組列表中出現頻率最高的 20 個單詞

如何查找數組列表中出現頻率最高的 20 個單詞

青春有我 2023-08-23 15:01:25
我有一個任務,給我一個帶有文本的文件。該文本是一本書的一部分。我的任務是將該文件傳輸到我所做的數組列表、哈希圖(其中之一)中。該工作的第二部分是從該文件中查找 20 個最常見的單詞,并按降序對它們進行排序。到目前為止,我將文件中的所有這些單詞插入到 hashmap 和 arraylist (下面提供了代碼),我在單獨的方法中完成了這兩件事。hashmap 方法僅返回數字,而 arraylist 只返回最常見的單詞以及重復次數。所以代碼的第一部分將是哈希圖public void findWords() throws Exception {    // ovde traxim 20 reci koje se najcesce ponavljaju u tekstu    String line;    Integer counter = 0;    FileReader fr = new FileReader("src/Fajl/blab");    BufferedReader br = new BufferedReader(fr);    while ((line = br.readLine()) != null) {        String string[] = line.toLowerCase().split("([,.\\s]+)");        for (String s : string) {            if (hashmap.containsKey(s)) {                counter++;            } else                counter = 1;            hashmap.put(s, counter);        }    }接下來的部分是按值排序,并顯示前 20 個單詞的重復次數,從多到少Collection<Integer> values = mapaKnjiga.values();    ArrayList<Integer> list = new ArrayList<Integer>(values);    Collections.sort(list, Collections.reverseOrder());    for (int i = 0; i < 20; i++)        System.out.println(list.get(i));}
查看完整描述

5 回答

?
紫衣仙女

TA貢獻1839條經驗 獲得超15個贊

將單詞視為哈希圖,其中單詞為鍵,計數為值。


LinkedHashMap<String, Integer> reverseSortedMap = new LinkedHashMap<>();


words.entrySet()

                .stream()

                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))

                .forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));


List<String> finalList = reverseSortedMap.entrySet()

                                        .stream()

                                        .map(entry -> entry.getKey())

                                        .limit(20)

                                        .collect(Collectors.toList());


查看完整回答
反對 回復 2023-08-23
?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

您可以創建一個類 TextCounter 并將其添加到基于地圖收集的數據的列表中


class TextCounter{

  String text;

  int count;

}

現在按他的計數值排序


查看完整回答
反對 回復 2023-08-23
?
慕姐8265434

TA貢獻1813條經驗 獲得超2個贊

假設您想要列出前 20 個單詞及其在地圖中的頻率,從文件中讀取單詞,java-8 解決方案將是


LinkedHashMap<String, Long> top20WordsByFrequency = null;

    try {

        // Convert a file into stream of lines

        top20WordsByFrequency = Files.lines(Paths.get("src/Fajl/blab"))

                // convert lines into words

                .flatMap(line -> Arrays.stream(line.toLowerCase().split("([,.\\\\s]+)")))

                // make a map by grouping by key as word and value as the count of the word

                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream()

                // sort the map based on values (frequency) in reverse order and limit the map

                // to 20

                .sorted(Entry.comparingByValue(Comparator.reverseOrder())).limit(20)

                // after limiting sort based on keys in descending order

                .sorted(Map.Entry.<String, Long>comparingByKey().reversed())

                // preserve the order in a LinkedHashMap

                .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (u, v) -> u, LinkedHashMap::new));


    } catch (IOException e) {

        e.printStackTrace();

    }

    System.out.println(top20WordsByFrequency);


查看完整回答
反對 回復 2023-08-23
?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

使用流 API 怎么樣:


String[] words = {"one", "two", "two", "three", "three", "three"};

Map<String, Long> result = 

        Arrays.stream(words)

              .collect(Collectors.groupingBy(Function.identity(),

                       Collectors.counting()));

第二部分:


List<Long> collect = result.entrySet().stream()

                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))

                .limit(20)

                .map(Map.Entry::getValue)

                .collect(Collectors.toList());

System.out.println(collect);


查看完整回答
反對 回復 2023-08-23
?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

假設您的 findWords() 函數工作正常,并且您擁有所有單詞及其計數,您可以執行以下操作:


因為您必須打印特定單詞的計數。因此,您可以首先定義一個具有屬性內容和計數的 Word 類,并定義一個默認比較器。如下所示:


class Item implements Comparable<Item>{

   String word;

   int count;


public Item(String word, int count){

    this.count = count;

    this.word = word;

}


public int compareTo(Item word){

    //sorting in descending order

    return word.count - this.count;

}


public String toString(){

    return "Word: " + word +"Count: " + count;

}}

定義一個項目 ArrayList 來保存 Item 對象:


ArrayList<Item> al = new ArrayList<>();

您可以迭代整個哈希圖,然后將每對插入為:


Item item = new Item(word, count);

al.add(item);

最后,您可以對列表進行排序,然后選擇前 20 個單詞:


Collections.sort(al);


查看完整回答
反對 回復 2023-08-23
  • 5 回答
  • 0 關注
  • 284 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號