赞
踩
题目:编写一个程序,统计一个文本文件所包含的不同单词的个数,并将结果保存在另一个文件中。输出文件的格式为:每个单词占用一行,其内容包括单词本身及其出现的次数;各单词之间要按照从小到大的顺序排列。
- import java.io.*;
- import java.util.*;
-
- /**
- * @author LL Leung
- */
- public class WordCount {
-
- static ArrayList<String> wordList = new ArrayList<String>();
-
- public static void main(String[] args)throws FileNotFoundException{
- //读入"word.txt"内容并存进字符串中
- Scanner input = new Scanner(new File("word.txt"));
- String s = input.nextLine();
-
- //分割字符串并存进字符串数组中
- String [] strArr = s.split(" ");
- HashMap<String, Integer> hashMap = new HashMap<String,Integer>();
-
- //遍历字符串数组
- for(String word:strArr){
- //求出不同单词个数
- if(!wordList.contains(word.toLowerCase())){
- wordList.add(word.toLowerCase());
- }
- //求出每一个单词出现的个数
- Integer currentCount = hashMap.get(word);
- if(currentCount == null){
- currentCount = 0;
- }
- hashMap.put(word,++currentCount);
- }
-
- System.out.println("不同单词个数为:" + wordList.size());
-
- //创建新文件"newDemo2.txt"并将"排序单词出现次数"等内容存进新文件中
- try{
- FileOutputStream fos = new FileOutputStream("newDemo.txt",false);
- fos.write(sort(hashMap).getBytes());
- //关闭文件流
- fos.close();
- }catch(IOException ex){
- System.out.println("无法打开文件!");
- }
- }
-
- /**
- * 将"hashMap"中的“value”值进行排序
- * @param hashMap
- * @return
- */
- public static String sort(Map<String,Integer> hashMap){
- StringBuilder str = new StringBuilder("不同单词个数为:" + wordList.size() + "\r\n");
- List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(hashMap.entrySet());
-
- Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
- @Override
- public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
- if (o1.getValue() < o2.getValue()) {
- return -1;
- } else if (o1.getValue() > o2.getValue()) {
- return 1;
- }
- return 0;
- }
- });
-
- //打印信息
- for (Map.Entry<String, Integer> id : list) {
- str.append("单词:").append(id.getKey()).append(" 出现次数:").append(id.getValue()).append("\r\n");
- }
- return str.toString();
- }
- }

原文本"word.txt"内容:
程序运行成功后创建的"newDemo.txt"文本:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。