0

我在让我的程序正常运行时遇到了一些麻烦。差不多完成了,除了这部分我已经工作了一个星期,但无法完成。程序应该计算每个单词出现的次数。

输入:

This is my file, yes my file My file.. ? ! , : ; / \ |" ^ * + = _( ) { } [ ] < >

输出应如下所示:

    file *3
    is *1
    my *3
    this *1
    yes *1

这是我的代码

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;

public class cleanup3 {

public cleanup3() {}

public static void main(String[] args) {   
  try{
     ArrayList myArraylist = new ArrayList();
     System.out.println("Please Enter file");

     InputStreamReader istream = new InputStreamReader(System.in) ;

     BufferedReader bufRead = new BufferedReader(istream) ;
     String fileName = bufRead.readLine();

     BufferedReader file = new BufferedReader(new FileReader(fileName));

     String s = null;
     while((s = file.readLine()) != null) {                      
         String updated2 = s.replaceAll("[\\.\\,\\?\\!\\:\\;\\/\\|\\\\\\^\\*\\+\\=\\_\\(\\)\\{\\}\\[\\]\\<\\>\"]+"," ");  

         //note to self: missing Single quotes (only if the LAST character of a token)
         StringTokenizer st = new StringTokenizer(updated2.toLowerCase());
         while (st.hasMoreTokens()) {
              String nextToken = st.nextToken();

              String myKeyValue = (String)myMap.get(nextToken);
              if(myKeyValue == null){
                  myMap.put(nextToken, "1");
              }
              else{
                  int mycount = Integer.parseInt(myKeyValue) + 1;
                  myMap.put(nextToken, String.valueOf(mycount));
              }
              System.out.println(nextToken);                           
           }   
        }
            System.out.println( updated2.toLowerCase());
            myArraylist.add(updated2.toLowerCase());                     
    }           
    Collections.sort(myArraylist);
    String outPutFileName =  fileName + "sorted.txt";         
    PrintStream ps = new PrintStream( outPutFileName );
    ps.print(myArraylist.toString());
    ps.flush();
    ps.close();        
  }
  catch (Exception e){
      System.out.println(e.toString());
  }
 }
4

2 回答 2

3

你的代码太复杂了——你只需要几行代码。

这是一种优雅的方法:

Map<String, Integer> map = new TreeMap<String, Integer>();
for (String word : input.toLowerCase().replaceAll("[^a-z ]", "").trim().split(" +"))
    map.put(word, map.containsKey(word) ? map.get(word) + 1 : 1);
for (Map.Entry<String, Integer> entry : map.entrySet())
    System.out.println(entry.getKey() + " *" + entry.getValue());

输入:

  • 折叠成小写,这可以解决大小写问题
  • 删除了所有非字母/空格,负责清理输入
  • 被修剪,这使输入准备好进行拆分
  • 在 1-n 个空格上分割
  • 被添加到累积总数的映射中,使用三元组来处理初始化单词total

然后迭代映射条目以输出总数。

使用 aTreeMap可以免费按字母顺序排序。

于 2013-06-06T01:14:22.650 回答
0

试试 BufferedReader 和 Regex,如下所示:

    Map<String, Integer> map = new HashMap<String, Integer>();
    String line;
    try (BufferedReader r = new BufferedReader(new FileReader(myFile))) {
            Pattern pattern = Pattern.compile("[a-zA-Z]+");
            while ((line = r.readLine())!=null) {
                Matcher matcher = pattern.matcher(line);
                while (matcher.find()) {
                    String word = matcher.group();
                    map.put(word, map.get(word) == null ? 1 : map.get(word)+1);
                }
            }
    }
    System.out.println(map.toString());
于 2013-06-06T02:40:38.750 回答