结对对象:严瑞 微博地址:http://www.cnblogs.com/yanrui666/p/5303941.html github:https://github.com/yanrui666/yanrui123/blob/master/作业4 贡献比例:50%/50%
基于作业3的结果,读取一个较小的文本文件A_Tale_of_Two_Cities.txt,统计该文件中的单词的频率,并将统计结果输出到当前目录下的 Result1.txt 文件。 (第一阶段初稿完成该要求)
- 命令行格式: 提示符> Myapp.exe -f filename.txt > Result.txt (PS:C++ 程序,Java 程序输出方式类似) filename.txt 为前面下载的文件名。
- 解释:
- 选项 -f 表示后面跟文件名
- 输出格式规定(参考作业3中的示例):
- 首先按照频率由高到低排序
- 频率一样的词, 按照字典顺序排序
- 此外, 读取一个较大的文本文件Gone_with_the_wind.txt实验对比程序执行效率,做如下改进,比较改进前后程序执行时间。
java文本文件调用:
BufferedReader infile = new BufferedReader(new FileReader("D:\\A_Tale_of_Two_Cities.txt"));
String string;
String file = null;
while ((string = infile.readLine()) != null) { file += string; }
java输出文本文件:
BufferedWriter bw = new BufferedWriter(new FileWriter("result1.txt"));
源程序:
import java.util.*;
import java.io.*;
public class WordsRate {public static void main(String[] args) throws Exception {
BufferedReader infile = new BufferedReader(new FileReader("D:\\A_Tale_of_Two_Cities.txt"));
String string;
String file = null;
while ((string = infile.readLine()) != null) { file += string; } file = file.toLowerCase();
file = file.replaceAll("[^A-Za-z]", " ");
file = file.replaceAll("\\s+", " ");
String words[];
words = file.split("\\s+");
Map<String, Integer> hashMap = new HashMap<String, Integer>();
for (int i = 0; i < words.length; i++) { String key = words[i];
if (hashMap.get(key) != null)
{
int value = ((Integer) hashMap.get(key)).intValue();
value++;
hashMap.put(key, new Integer(value)); } else { hashMap.put(key, new Integer(1)); } } Map<String, Object> treeMap = new TreeMap<String, Object>(hashMap);
Map<String, Object> treeMap1 = new TreeMap<String, Object>(hashMap);
BufferedWriter bw = new BufferedWriter(new FileWriter("result1.txt"));
Iterator iter = treeMap.entrySet().iterator();
String ss1[]=new String[treeMap.size()];;
int ss2[]=new int[treeMap.size()];
int i=0;
while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next();
int val = (Integer)entry.getValue();
String key =(String) entry.getKey();
ss1[i]=key;
ss2[i]=val;
i++;
}
int sValue=0;
String sKey="";
for(int j=0;j<ss2.length;j++)
{
for(int k=0;k<i;k++)
{
if(ss2[j]>ss2[k])
{ sValue=ss2[j];
sKey=ss1[j];
ss2[j]=ss2[k];
ss1[j]=ss1[k];
ss2[k]=sValue;
ss1[k]=sKey;
}
}
}
int[] strLengths = new int[ss2.length];
for(int j=0 ;j<ss2.length; j++){ strLengths[j] = ss1[j].length(); }
for(int j=0;j<ss2.length;j++){ if(strLengths[j]>=4) System.out.println(ss1[j]+"="+ss2[j]); bw.write(ss1[j]+"="+ss2[j]); bw.newLine(); bw.flush(); }
}
}
结果:
心得:两个人结对比自己轻松多了,有些问题自己找不出对方就解决了,很方便