拆分方法不区分特殊字符

时间:2018-12-10 04:26:55

标签: java

我正在开发一个程序,该程序可以计算文本文件中单词的出现率。该程序可以编译并运行良好,但是我尝试使用split方法从单词中分离特殊字符(例如.,;:!?(){})。

这是一个输出示例

 6       eyes,
 3       eyes.
 2       eyes;
 1       eyes?
 1       eyrie

您可以看到拆分功能不起作用。我已经尝试调试,但到目前为止还没有运气。谁能指出我正确的方向或告诉我我做错了什么。谢谢。

import java.util.*;
import java.io.*;

    public class testingForLetters {
        public static void main(String[] args) throws FileNotFoundException {
    // open the file
    Scanner console = new Scanner(System.in);
    System.out.print("What is the name of the text file? ");
    String fileName = console.nextLine();
    Scanner input = new Scanner(new File(fileName));


    // count occurrences
    Map<String, Integer> wordCounts = new TreeMap<String, Integer>();
    while (input.hasNext()) {

        input.next().split("[ \n\t\r.,;:!?(){}]" );
        String next = input.next().toLowerCase();


        if (next.startsWith("a") || next.startsWith("b") || next.startsWith("c") || next.startsWith("d") || next.startsWith("e") )  {

          if (!wordCounts.containsKey(next)) {
              wordCounts.put(next, 1);
          } else {
              wordCounts.put(next, wordCounts.get(next) + 1);
          }

        }
    }
    // get cutoff and report frequencies
    System.out.println("Total words = " + wordCounts.size());
    for (String word : wordCounts.keySet()) {
        int count = wordCounts.get(word);
        System.out.println(count + "\t" + word);

     }
  }
}

1 个答案:

答案 0 :(得分:3)

.split()方法返回一个字符串数组,现在您没有将input.next().split()设置为等于任何值。您必须创建一个数组并将其设置为等于input.next().split(),然后从该数组中获取单词。基本上,您需要完全像设置.toLowerCase()的{​​{1}}部分那样处理它。希望这会有所帮助。