簡體   English   中英

嘗試創建一個哈希表以從文本文件中獲取 arraylist - Java

[英]Trying to create a hashtable to get an arraylist from the text file - Java

我正在嘗試創建一個哈希表以從我的文本文件中獲取ArrayList讀取它,然后將其計入另一個文本文件。 我應該標記每個單詞並通過計數來獲取鍵和值。 到目前為止,我還處於起步階段,我不知道我的代碼有什么問題,似乎沒有錯誤,但它沒有連接到文本並獲得ArrayList或者只是我的代碼錯誤。 我將不勝感激任何幫助。 謝謝。

這是 Map 文件


public class Map {
    public static String fileName= "C:Users\\ruken\\OneDrive\\Desktop\\workshop.txt";

    private ArrayList<String> arr = new ArrayList<String>();
    public ArrayList <String>getList () {
        return this.arr;
    }

    private Hashtable<String, Integer> map = new Hashtable<String, Integer>();

    public void load(String path) {
        try{
            FileReader f2 = new FileReader("C:Users\\ruken\\OneDrive\\Desktop\\workshop.txt");
            Scanner s = new Scanner(f2);
            while (s.hasNextLine()) {
                String line = s.nextLine();
                String[] words = line.split("\\s");
                for (int i=0;i<words.length; i++){
                    String word = words[i];
                    if (! word.isEmpty()){
                        System.out.println(word);
                        arr.add(word);
                    }
                }
            }
            f2.close();
            System.out.println("An error occurred");
        }
        catch(IOException ex1)
        {
            Collections.sort(arr);
            System.out.println("An error occurred.");
            for (String counter: arr) {
                System.out.println(counter);
            }
            ex1.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Map m =new Map();
        m.load("C:Users\\ruken\\OneDrive\\Desktop\\out.txt");
    }


    public Object get(String word) {
        return null;
    }

    public void put(String word, int i) {

    }


}

這是減少文件

package com.company;

import java.io.*;
import java.util.*;

public class Reduce {

    private Hashtable<String, Integer> map=new Hashtable< String, Integer>();

    public Hashtable < String, Integer> getHashTable () {
        return map;
    }

    public void setHashTable ( Hashtable < String, Integer> map){
        this.map =map;
    }

    public void findMin () {

    }

    public void findMax() {

    }

    public void sort (ArrayList<String> arr) throws IOException {
        Collections.sort(arr);
        Iterator it1 = arr.iterator();
        while (it1.hasNext()) {
            String word = it1.next().toString();
            System.out.println(word);

        }
    }
    //constructors
    public void reduce (ArrayList<String> words) {
        Iterator<String> it1 =words.iterator();
        while (it1.hasNext()) {
            String word=it1.next();
            System.out.println (word);
            if (map.containsKey(word)) {
                map.put(word, 1);
            }
            else {
                int count = map.get(word);
                map.put(word, count+1);
            }

            System.out.println( map.containsValue(word));


            }
        }


    }

這是workshop.txt的一部分。 這是基本的簡單文本

" 致謝

我要感謝 Carl Fleischhauer 和 Prosser Gifford 有機會了解我在十個月前還不知道的人類活動領域,以及大衛和露西爾帕卡德基金會支持這個機會。 其他人提供的幫助在單獨的頁面上得到確認。

                                                      19 October 1992


           ***   ***   ***   ******   ***   ***   ***


                          INTRODUCTION

電子文本研討會 (1) 匯集了來自不同項目和利益集團的代表,以比較思想、信仰、經驗,尤其是以計算機化形式放置和呈現歷史文本材料的方法。 大多數與會者從活動中獲得了很多見識和 outlook。 但大會並沒有形成一個新的國家,或者換句話說,項目和利益的多樣性太大,無法將代表們吸引到一個有凝聚力的、以行動為導向的機構中。(2)"

可以使用 java stream API來計算文本中的詞頻

這是我的實現,后面是解釋性說明。

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public class WordFreq {

    public static void main(String[] args) {
        Path path = Paths.get("workshop.txt");
        Function<String, String> keyMapper = Function.identity();
        Function<String, Integer> valueMapper = (word) -> Integer.valueOf(1);
        BinaryOperator<Integer> mergeFunction = (a, b) -> Integer.valueOf(a.intValue() + b.intValue());
        Supplier<Hashtable<String, Integer>> mapSupplier = () -> new Hashtable<>();
        try {
            Map<String, Integer> map = Files.lines(path)
                 .flatMap(line -> Arrays.stream(line.split("\\b")))
                 .filter(word -> word.matches("^\\w+$"))
                 .map(word -> word.toLowerCase())
                 .collect(Collectors.toMap(keyMapper, valueMapper, mergeFunction, mapSupplier));
            BiConsumer<String, Integer> action = (k, v) -> System.out.printf("%3d %s%n", v, k);
            map.forEach(action);
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}
  • class java.nio.file.Files中的方法lines()創建文件中文本行的stream。 在這種情況下,該文件是您的Workshop.txt文件。
  • 對於讀取的文件的每一行,我使用 class java.lang.String中的方法 split() 將其拆分為單詞,並將方法split() split()的數組轉換為另一個 ZF7B44CFAFD5C52223D7498196BZ8A。
  • 實際上,每一行文本都在每個單詞邊界處拆分,因此split()方法返回的單詞數組可能包含不是真正單詞的字符串。 因此,我過濾“單詞”以便僅提取真實單詞。
  • 然后我將每個單詞轉換為小寫,這樣我的最終 map 將不區分大小寫。 換句話說,單詞The和單詞the將被認為是同一個單詞。
  • Finally I create a Map where the map key is a distinct word in the text of file workshop.txt and the map value is an Integer which is the number of occurrences of that word in the text.

由於您規定Map必須是Hashtable ,所以我明確創建了一個Hashtable來存儲 stream 上的collect操作的結果。

上面代碼的最后一部分顯示了Hashtable的內容。

我整理了第一部分“地圖”,如下所示,現在我有一個按字母排序的數組。 如下..現在我應該計算標記化的鍵值。 “..然而還沒有讓你年輕的熱情為零。縮放……”

package com.company;


        import java.io.FileReader;
        import java.io.IOException;
        import java.util.*;
        import java.util.Collections;

public class Map {

    public static String fileName= "C:\\Users\\ruken\\OneDrive\\Desktop\\workshop.txt";



    private ArrayList<String> arr = new ArrayList<String>();
    public ArrayList <String>getList () {
        return this.arr;
    }

    private Hashtable<String, Integer> map = new Hashtable<String, Integer>();

    public void load() {



        try{
            FileReader f2 = new FileReader("C:\\Users\\ruken\\OneDrive\\Desktop\\workshop.txt");

            Scanner s = new Scanner(f2);
            while (s.hasNextLine()) {
                String line = s.nextLine();
                String[] words = line.split("\\s");
                for (int i=0;i<words.length; i++){
                    String word = words[i];
                    if (! word.isEmpty()){
                        System.out.println(word);
                        arr.add(word);
                    }
                }
            }
            f2.close();
            System.out.println();


    }
            catch(IOException ex1){
                System.out.println("An error occurred.");
             ex1.printStackTrace(); }
        {
            Collections.sort(arr);
            System.out.println("Sorted.");
            for (String counter: arr) {
                System.out.println(counter);
            }

        }

    }

    public static void main(String[] args) {
        Map m =new Map();
        m.load();
    }
}

進行減少的第二部分是:


package com.company;


import java.io.*;
import java.util.*;
import java.io.FileWriter;
import java.io.IOException;

public class Reduce {

    private Hashtable<String, Integer> map = new Hashtable<String, Integer>();


    public Hashtable<String, Integer> getHashTable() {
        return map;
    }

    public void setHashTable(Hashtable<String, Integer> map) {
        this.map = map;
    }


    //constructors
    public void reduce (ArrayList<String> arr) {
        Iterator<String> it1 = arr.iterator();
        while (it1.hasNext()) {
            String word = it1.next();
            System.out.println(word);
            if (map.containsKey(word)) {
                int a = (int) map.get(word);
                a++;
                map.put(word, a);
            } else {
                map.put(word, 1);
            }
        }
    }



    public void write () {

        try {
            FileWriter f1 = new FileWriter("C:\\Users\\ruken\\OneDrive\\Desktop\\output.txt");
            Iterator<String> it1 = map.keySet().iterator();
            while (it1.hasNext()) {
                String word = it1.next().toString();
                f1.write(word + "" + ":" + "" + map.get(word) + "\n" );
            }
            f1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args)  {

        Map m =new Map();
        m.load();
        Reduce r = new Reduce ();
        ArrayList<String> arr=  m.getList();
        r.reduce(arr);
        r.write();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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