java - 计数文章 "a","an"在文本文件中被使用的次数

标签 java counting

我正在尝试制作一个程序来计算单词、行、句子的数量,以及文章“a”、“and”、“the”的数量。 到目前为止,我得到了单词、行、句子。但是我不知道我要统计谁的文章。程序如何区分“a”和“and”。

到目前为止这是我的代码。

 public static void main(String[]args) throws FileNotFoundException, IOException        
    {       
FileInputStream file= new FileInputStream("C:\\Users\\nlstudent\\Downloads\\text.txt");
Scanner sfile = new Scanner(new File("C:\\Users\\nlstudent\\Downloads\\text.txt"));

  int ch,sentence=0,words = 0,chars = 0,lines = 0; 

  while((ch=file.read())!=-1)
  {
   if(ch=='?'||ch=='!'|| ch=='.')
    sentence++;
  }

    while(sfile.hasNextLine())  {
        lines++;
    String line = sfile.nextLine();
        chars += line.length();
        words += new StringTokenizer(line, " ,").countTokens();
    }


System.out.println("Number of words: " + words);
System.out.println("Number of sentence: " + sentence);
System.out.println("Number of lines: " + lines);
System.out.println("Number of characters: " + chars);
}
}

最佳答案

How can a program make the difference between 'a' and 'and'.

您可以为此使用正则表达式:

        String input = "A and Andy then the are a";
        Matcher m = Pattern.compile("(?i)\\b((a)|(an)|(and)|(the))\\b").matcher(input);
        int count = 0;
        while(m.find()){
            count++;
        }
        //count == 4

'\b'是一个单词边界,'|'是 OR,'(?i)' - 忽略大小写 标志。您可以找到的所有模式列表 here或许您应该了解正则表达式。

关于java - 计数文章 "a","an"在文本文件中被使用的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28569490/

相关文章:

java - Eclipse junit View 中的不可打印字符

python - 执行计数、排序/映射大型字典

php - 计算字符串中位数的函数

c# - 计算 C#/.NET 网页中出现的 1 个词、2 个词和 3 个词短语

计数排序算法在 C 中不起作用

java.net.SocketException : Connection reset (SSL) 异常

java - Netbeans Swing GUI Builder 无法与 java 模块项目和 Maven 一起使用

java - 无法将 jar 从 MavenLocal 导入 Android Studio - 意外的顶级异常 : finished with non-zero exit value 1

java - 在JAVA中只解析一次XML文件

python - Pandas :如何计算考虑到以前记录的变化数量