又是一天JAVA课,今天我们要做的竟然是训练机器读《哈利波特》!
说是读,其实就是做一个统计字词数的程序,代码如下:
package hellopeace; import java.io.*; import java.util.*; public class ByteArrayStreamDemo { public static void main(String[] args) { try { int[] times=new int[100000]; String[] names=new String[100000]; int p=0; File file = new File("C:\\Users\\14997\\Desktop\\哈利波特英文版\\Harry Potter And The Chamber Of Secrets.txt"); BufferedInputStream bufferedInputStream = new BufferedInputStream( new FileInputStream(file)); ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); byte[] bytes = new byte[100]; // 将文件内容写入位数组流 int poi=0; int rop=0; int []poc=new int[26]; while(bufferedInputStream.read(bytes) != -1) { arrayOutputStream.write(bytes); } arrayOutputStream.close(); bufferedInputStream.close(); bytes = arrayOutputStream.toByteArray(); String eop=""; int cd=0; for(int i = 0; i < bytes.length; i++) { if(((char) bytes[i]>='A'&&(char) bytes[i]<='Z')) { poi++; poc[(int)((char) bytes[i]-'A')]++; eop=eop+(char) bytes[i]; } else if(((char) bytes[i]>='a'&&(char) bytes[i]<='z')) { poi++; poc[(int)((char) bytes[i]-'a')]++; eop=eop+(char) bytes[i]; } else { if(!eop.equals("")) { for(int d=0;d<cd;d++) { if(names[d].equalsIgnoreCase(eop)){ times[d]++;p=10; } } if(p==0) { names[cd]=eop; times[cd]++; eop=""; cd++; } p=0; } } } int n=0; Scanner in=new Scanner(System.in); n=in.nextInt(); int[] pop=new int[100000]; int sr=0;int so=0,st=50000000; String x="",sc="",se="",ho=""; for(int i=0;times[i]!=0;i++){ for(int j=0;times[j]!=0;j++){ if((times[j]>so)&&(names[j]!=x)&&(times[j]<st)&&(names[j]!=se)){ so=times[j]; sc=names[j]; sr=j; } } st=so; se=x; x=sc; pop[i]=sr; so=0; } Random rand=new Random(); for(int i=0;i<n&×[pop[i]]!=0;i++) { System.out.print(names[pop[i]]+" "); System.out.println(times[pop[i]]); } } catch(IOException e) { e.printStackTrace(); } } }
话说这好久没写JAVA了,突然这么一下还真不太适应(笑)