简体   繁体   English

使用stringtokenizer来计算单词问题

[英]using stringtokenizer to count word issue

I have some trouble getting my program to run as it should. 我无法按计划运行我的程序。 It's about done except for this part i have been working on for a week now and cant get it. 除了这一部分,我已经完成了一个星期,现在无法完成它。 The program should count the number of times each word occurs. 该程序应计算每个单词出现的次数。

With an input of : 输入:

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

the output should look like this: 输出应如下所示:

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

here is my code 这是我的代码

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());
  }
 }

Your code is way too complicated - you only need a few lines of code. 您的代码太复杂了-您只需要几行代码。

Here's the elegant way to do it: 这是一种优雅的方法:

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());

The input: 输入:

  • is folded to lowercase, which takes care of the case issues 折叠成小写字母,这可以解决大小写问题
  • has all non-letters/spaces removed, which takes care of cleaning the input 删除了所有非字母/空格,这有助于清理输入
  • is trimmed, which gets the input ready for splitting 修剪,使输入准备好进行拆分
  • is split on 1-n spaces 在1-n个空间上分割
  • is added to a map which accumulates the totals, employing a ternary to handle initialising the word total 被添加到累积总数的地图中,使用三元数来处理单词total的初始化

The map entries are then iterated to output the totals. 然后,迭代映射条目以输出总计。

Using a TreeMap takes care of ordering alphabetically for free. 使用TreeMap可以免费按字母顺序排序。

Try BufferedReader and Regex, like so: 尝试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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM