【问题标题】:java read vowels from text filejava从文本文件中读取元音
【发布时间】:2016-09-26 00:24:25
【问题描述】:

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

所以这是一个例子 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.
  */

【问题讨论】:

  • 你能发布你的代码吗?
  • 你为什么不发布你的代码?
  • 你希望它按句还是按行计算?
  • 感谢 cmets。但是我对在 java.lang 中寻找它感到非常盲目,以至于我忘记了 java 是顺序的。在循环结束时将元音设置回零将解决此问题。
  • 如果您的代码 sn-p 无法运行,则不应使用“运行代码 sn-p”功能。话虽如此,我赞成你的问题。

标签: java string text-files counter


【解决方案1】:

我创建了一个简单的类来实现我认为您的目标。 vowelTotal 重置,这样您就不会遇到您提到的句子的元音相互添加的问题。我假设通过查看我的代码,您可以看到自己的解决方案?此外,此代码假定您包含“y”作为元音,并且还假定句子以正确的标点符号结尾。

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
            }
        }
    }
}

【讨论】:

  • 您还有另一个主要假设。试试这个段落:I showed my solution to my professor, Dr. Black, but she told me there was a problem with it.
  • 哇,我没想到。感谢您指出这一点。
  • 是的——但我真的不知道一个好的解决方案,除非假设没有任何缩写。
  • 我能想到的唯一方法是使用 if 语句排除所有使用的事物,例如“Sr.”、“Jr.”、“Mt.”等。它们显然不会被用作单词,所以它至少有助于解决一些例外情况。
  • 是的,这是个好主意。但是您必须开始将句子分解为单词,而您的代码目前还没有这样做。无论如何,看起来您的答案对于 OP 的目的来说已经足够了。
【解决方案2】:

也许不是最优雅的方法,但可以快速计算每个句子中的元音我想出这个,测试并工作(至少使用我的测试字符串):

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

【讨论】:

    【解决方案3】:

    这里有一个完整的例子来计算文件中每个句子中元音的数量。它使用了一些先进的技术:(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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多