java从文本文件中读取元音

时间:2016-09-26 00:24:26

标签: java string text-files counter

我正在创建一个从文本文件中读取元音的程序。这段文字很长,我希望程序能够计算每个句子的元音。

所以这是一个例子 7个元音

另一个 3个元音

到目前为止,我已经编写了能够读取元音的代码。但是,它将其视为一个额外的整体。在循环中它将首先计数7然后第二行将其输出为10.我希望它输出7作为第一行而3作为第二行。

我正在查看java中的String API,但我没有看到任何可以帮助解决这个问题的方法。我正在计算元音的方式是使用一个for循环来循环使用Charat()。我错过了什么,或者没有办法阻止它阅读并加入计数器?

这是一个例子

    while(scan.hasNext){
      String str = scan.nextLine();
      for(int i = 0; i<str.length(); i++){
        ch = str.charAt(i);
        ...
        if(...)
          vowel++;
        }//end for
      S.O.P();
        vowel = 0;//This is the answer... Forgotten that java is sequential...
      }

    }// end main()
  }//end class

  /*output:
  This sentence have 7 vowels.
  This sentence have 3 vowels.
  */

3 个答案:

答案 0 :(得分:2)

我创建了一个简单的类来实现我相信你的目标。元音总重置,以便你不会遇到你提到的句子的问题&#39;元音互相添加。我假设通过查看我的代码,您可以看到自己的解决方案吗?此外,此代码假定您包含&#34; y&#34;作为一个元音,它也假设句子以正确的标点符号结束。

public class CountVowels{
    String paragraph;
    public CountVowels(String paragraph){
        this.paragraph = paragraph;
        countVowels(paragraph);
    }

    int vowelTotal = 0;
    int sentenceNumber = 0;
    public void countVowels(String paragraph){
        for(int c = 0; c < paragraph.length(); c++){
            if( paragraph.charAt(c) == 'a' || paragraph.charAt(c) == 'e' || paragraph.charAt(c) == 'i' || paragraph.charAt(c) == 'o' || paragraph.charAt(c) == 'u' || paragraph.charAt(c) == 'y'){
                vowelTotal++; //Counts a vowel
            } else if( paragraph.charAt(c) == '.' || paragraph.charAt(c) == '!' || paragraph.charAt(c) == '?' ){
                sentenceNumber++; //Used to tell which sentence has which number of vowels
                System.out.println("Sentence " + sentenceNumber + " has " + vowelTotal + " vowels.");
                vowelTotal = 0; //Resets so that the total doesn't keep incrementing
            }
        }
    }
}

答案 1 :(得分:1)

也许不是最优雅的方式,但真正快速计算每个句子中的元音,我想出了这个,测试和工作(至少用我的测试字符串):

String testString = ("This is a test string. This is another sentence. " +
            "This is yet a third sentence! This is also a sentence?").toLowerCase();
    int stringLength = testString.length();
    int totalVowels = 0;
    int i;

        for (i = 0; i < stringLength - 1; i++) {
            switch (testString.charAt(i)) {
                case 'a':
                case 'e':
                case 'i':
                case 'o':
                case 'u':
                    totalVowels++;
                    break;
                case '?':
                case '!':
                case '.':
                    System.out.println("Total number of vowels in sentence: " + totalVowels);
                    totalVowels = 0;
            }

        }

    System.out.println("Total number of vowels in last sentence: " + totalVowels);

答案 2 :(得分:1)

这是一个完整的例子来计算文件每个句子中的元音数量。它使用了一些先进的技术:(1)将段落分成句子的正则表达式; (2)HashSet数据结构,用于快速检查字符是否为元音。该程序假定文件中的每一行都是一个段落。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CountVowels {

    // HashSet of vowels to quickly check if a character is a vowel.
    // See usage below.
    private Set<Character> vowels =
        new HashSet<Character>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'y'));

    // Read a file line-by-line. Assume that each line is a paragraph.
    public void countInFile(String fileName) throws IOException {

        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String line;

        // Assume one file line is a paragraph.
        while ((line = br.readLine()) != null) {
            if (line.length() == 0) {
                continue; // Skip over blank lines.
            }
            countInParagraph(line);
        }

        br.close();
    }

    // Primary function to count vowels in a paragraph. 
    // Splits paragraph string into sentences, and for each sentence,
    // counts the number of vowels.
    private void countInParagraph(String paragraph) {

        String[] sentences = splitParagraphIntoSentences(paragraph);

        for (String sentence : sentences) {
            sentence = sentence.trim(); // Remove whitespace at ends.
            int vowelCount = countVowelsInSentence(sentence);
            System.out.printf("%s : %d vowels\n", sentence, vowelCount);
        }
    }

    // Splits a paragraph string into an array of sentences. Uses a regex.
    private String[] splitParagraphIntoSentences(String paragraph) {
        return paragraph.split("\n|((?<!\\d)\\.(?!\\d))");
    }

    // Counts the number of vowels in a sentence string.
    private int countVowelsInSentence(String sentence) {

        sentence = sentence.toLowerCase();

        int result = 0;    
        int sentenceLength = sentence.length();

        for (int i = 0; i < sentenceLength; i++) {
            if (vowels.contains(sentence.charAt(i))) {
                result++;
            }
        }

        return result;
    }

    // Entry point into the program.
    public static void main(String argv[]) throws IOException {

        CountVowels cw = new CountVowels();

        cw.countInFile(argv[0]);
    }
}

对于此文件example.txt:

So this is an example. Another.

This is Another line.

结果如下:

% java CountVowels example.txt
So this is an example : 7 vowels
Another : 3 vowels
This is Another line : 7 vowels