2021年7月22日 星期四

JAVA IO套件-05 讀檔與計算字數

  上次說要做的練習,讀取英文文字檔案並計數裡面出現的每一個字。

讀取類別:將文字檔案讀取後存成一維陣列,

import java.io.*;
public class ReadAsRaw {
String fileName;
int x;

// 字串讀取方法,就是英文單字,這個方法讀取存成一維陣列。
public String[] readStringFile(String fileName,int x) throws IOException{
this.fileName = fileName;
this.x = x;
int total = 0;
String[] stringArry = new String[x];
if( new File(fileName).exists()) {
BufferedReader fileString = new BufferedReader(new FileReader(fileName));
String line;
while ((line = fileString.readLine()) != null) {
String [] unit = line.split("\\W+"); // 用一個或多個非字母字元分割字串。
int size = unit.length;
for (int i = 0; i < size; i++){
stringArry[total + i] = unit[i];
}
total=total+size;
}
fileString.close();
}
else {
System.out.println("沒有 " + fileName + " 登!登!");
}
System.out.println("總字數:"+ total);
return stringArry;
}

}

字數計算類別:計數丟入的一維字串陣列中的每個單字出現次數。

import java.util.HashMap;

public class WordCount {

public void wordsCount(String[] sentence) {
// TODO Auto-generated method stub
String[] words = sentence ;//sentence.split("\\W+");
//新建一個 HashMap
HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
int j = 0;
for (int i = 0; i < words.length; i++) {
if (hashMap.get(words[i]) == null) {
hashMap.put(words[i], 1); //如果 hashMap 中沒有那個單詞,設定值為 1
}
else { //如果 hashMap 中有這個單詞,則將該單詞的值加 1
hashMap.put(words[i], hashMap.get(words[i]) + 1);
j++;
}
}
System.out.println(" " + j + " 個不同的單字");
for(int i = 0; i < j; i++) {
System.out.println(words[i] + " ; " + hashMap.get(words[i]));
}

}
}

主程式:事先必須準備好一個文字檔於在專案資料夾中,例如 test.txt 。

public class Main {
public static void main(String[] args) throws Exception{

ReadAsRaw rW = new ReadAsRaw();
String nameString = "test.txt";
int guessTotal=313; // 猜總字數,可以大於等於,不能小於真實的字數。
String[] sArry = rW.readStringFile(nameString, guessTotal);

WordCount cW = new WordCount();
cW.wordsCount(sArry);
//System.out.println(cW.);
}
}

結果:因為太長,所我中間省略了,前面單字,後面數字。

總字數:313
有 137 個不同的單字
Quantum  ;  3
mechanics  ;  8
is  ;  4
a  ;  7
fundamental  ;  1

中間略

are  ;  2
restricted  ;  1
to  ;  7
discrete  ;  1

Process finished with exit code 0

  這邊用分號是因為試算表可以用分號當分隔符號,方便大家後續的操作。這個程式還有一件事情我沒有做,那就是排序。暫時懶得寫。最近有其他目標,下次練習應該是一段時間後了。

  為了完成這個練習,我所找到的程式參考來源:https://www.itread01.com/p/1432610.html;另外還有一個別人已經寫好,放在網路上分享的字數統計工具:https://blog.qqboxy.com/2016/06/english-word-analyze.html



沒有留言:

張貼留言