分析:
1)要統計單詞的個數,就自己的對文章中單詞出現的判斷的理解來說是:當出現一個非字母的字符的時候,對前面的一部分字符串歸結為單詞
2)對於最后要判斷字母出現的個數這個問題,我認為應該是要用到map比較合適吧,因為map中有 鍵-值 的關系,可以把字符串設置為鍵,把出現的個數設置為整型,這樣就能夠建立起一一對應的關系,不用再判斷所在的位置
根據上面自己的理解,今天我寫了以下的一部分代碼,對哈利波特第一集的這部分文章進行了單詞的統計的測試,測試的結果相對良好,沒有問題。
package pipei; //洪鼎淇 20173627 信1705-3 import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.Map; //哈利波特單詞統計 public class Pipei { public Map<String,Integer> map1=new HashMap<String,Integer>(); public static void main(String arg[]) { String sz[]; Integer num[]; final int MAXNUM=10; //統計的單詞出現最多的前n個的個數 sz=new String[MAXNUM+1]; num=new Integer[MAXNUM+1]; Pipei pipei=new Pipei(); int account =1; //Vector<String> ve1=new Vector<String>(); try { pipei.daoru(); } catch (IOException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } System.out.println("英文單詞的出現情況如下:"); int g_run=0; for(g_run=0;g_run<MAXNUM+1;g_run++) { account=1; for(Map.Entry<String,Integer> it : pipei.map1.entrySet()) { if(account==1) { sz[g_run]=it.getKey(); num[g_run]=it.getValue(); account=2; } if(account==0) { account=1; continue; } if(num[g_run]<it.getValue()) { sz[g_run]=it.getKey(); num[g_run]=it.getValue(); } //System.out.println("英文單詞: "+it.getKey()+" 該英文單詞出現次數: "+it.getValue()); } pipei.map1.remove(sz[g_run]); } int g_count=1; String tx1=new String(); for(int i=0;i<g_run;i++) { if(sz[i]==null) continue; if(sz[i].equals("")) continue; tx1+="出現次數第"+(g_count)+"多的單詞為:"+sz[i]+"\t\t\t出現次數: "+num[i]+"\r\n"; System.out.println("出現次數第"+(g_count)+"多的單詞為:"+sz[i]+"\t\t\t出現次數: "+num[i]); g_count++; } try { pipei.daochu(tx1); } catch (IOException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } } public void daoru() throws IOException { File a=new File("1.Harry Potter and the Sorcerer's Stone.txt"); FileInputStream b = new FileInputStream(a); InputStreamReader c=new InputStreamReader(b,"UTF-8"); String string2=new String(); while(c.ready()) { char string1=(char) c.read(); if(!isWord(string1)) { if(map1.containsKey(string2)) { Integer num1=map1.get(string2)+1; map1.put(string2,num1); } else { Integer num1=1; map1.put(string2,num1); } string2=""; } else { string2+=string1; } } if(!string2.isEmpty()) { if(map1.containsKey(string2)) { Integer num1=map1.get(string2)+1; map1.put(string2,num1); } else { Integer num1=1; map1.put(string2,num1); } string2=""; } c.close(); b.close(); } public void daochu(String txt) throws IOException { File fi=new File("tongji.txt"); FileOutputStream fop=new FileOutputStream(fi); OutputStreamWriter ops=new OutputStreamWriter(fop,"UTF-8"); ops.append(txt); ops.close(); fop.close(); } public boolean isWord(char a) { if(a<='z'&&a>='a'||a<='Z'&&a>='A') return true; return false; } }
測試截圖:
這是出現的單詞的截圖情況,對於其中出現s的情況的分析,s其實是單詞里面的縮寫,一般往往有It's 這種情況的出現,為了避免這種情況,我對文中的某一部分進行修改(修改部分如下圖),將It's看成一部分
isWord函數判斷是否為字母的這一部分將單引號也作為一個符號放進去
修改完之后的測試如下:
搞定!!