计算文本文件中的句子数

时间:2015-02-02 19:11:49

标签: java

句子我猜是字符串结束了! ?

除了Mr. Dr.先生之类的东西 确实,由于语法,你无法真正知道java中的一个句子。

但我想我的意思是句号或感叹号或问号,然后是大写字母。

如何做到这一点。

这就是我所拥有的 但它不起作用......

      BufferedReader Compton = new BufferedReader(new FileReader(fileName));
        int sentenceCount=0;

        String violet;

        String limit="?!.";
        while(Compton.ready())
        {
            violet=Compton.readLine();

            for(int i=0; i<violet.length()-1;i++)
            {
                if(limit.indexOf(violet.charAt(i)) != -1 && i>0 && limit.indexOf(violet.charAt(i-1)) != -1)
                {
                    sentenceCount++;
                }
            }
        }
            System.out.println("the amount of sentence is " + sentenceCount);

EDIT 更好的新方法

          String violet;
        while(Compton.ready())
        {
            violet=Compton.readLine();
            sentenceCount=violet.split("[!?.:]+").length;
            System.out.println("the number of words in line is " + 

              sentenceCount);
         }

3 个答案:

答案 0 :(得分:3)

BufferedReader reader = new BufferedReader(new FileReader(fileName));
int sentenceCount = 0;
String line;
String delimiters = "?!.";

while ((line = reader.readLine()) != null) { // Continue reading until end of file is reached
    for (int i = 0; i < line.length(); i++) {
        if (delimiters.indexOf(line.charAt(i)) != -1) { // If the delimiters string contains the character
            sentenceCount++;
        }
    }
}

reader.close();
System.out.println("The number of sentences is " + sentenceCount);

答案 1 :(得分:0)

一个班轮:

int n = new String (Files.readAllBytes(Paths.get(path))).split ("[\\.\\?!]").length

使用Java 7构造将整个文件读取到字节数组,从中创建一个字符串并拆分成句子数组然后获取数组的长度。

答案 2 :(得分:0)

执行此操作的一种可能方法是将文件扫描为单词,然后计算不在您的例外列表中以给定标点符号结尾的单词。

这是使用Java 8流的可能实现:

List<String> exceptions = Arrays.toList("Dr.", "Mr.");
Iterable<String> iterableScanner = () -> new Scanner(filename);
int sentenceCount = StreamSupport.stream(iterableScanner, false)
    .filter(word -> word.matches(".*[\\.\\?!]))
    .filter(word -> !exceptions.contains(word))
    .count();