我正在尝试使用 BufferedReader 构建一个程序,该程序读取文件并跟踪元音、单词,并且可以计算每行的平均单词数。我已经有了读取文件的框架,但我真的不知道从这里到哪里去读取它。任何帮助,将不胜感激。谢谢。
import java.io.*;
public class JavaReader
{
public static void main(String[] args) throws IOException
{
String line;
BufferedReader in;
in = new BufferedReader(new FileReader("message.txt"));
line = in.readLine();
while(line != null)
{
System.out.println(line);
line = in.readLine();
}
}
}
最佳答案
这就是我得到的。字数统计是有问题的,但对于我将给出的一个例子来说是有效的。可以做出改变(我接受批评)。
import java.io.*;
public class JavaReader
{
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader("message.txt"));
String line = in.readLine();
// for keeping track of the file content
StringBuffer fileText = new StringBuffer();
while(line != null) {
fileText.append(line + "\n");
line = in.readLine();
}
// put file content to a string, display it for a test
String fileContent = fileText.toString();
System.out.println(fileContent + "--------------------------------");
int vowelCount = 0, lineCount = 0;
// for every char in the file
for (char ch : fileContent.toCharArray())
{
// if this char is a vowel
if ("aeiou".indexOf(ch) > -1) {
vowelCount++;
}
// if this char is a new line
if (ch == '\n') {
lineCount++;
}
}
double wordCount = checkWordCount(fileContent);
double avgWordCountPerLine = wordCount / lineCount;
System.out.println("Vowel count: " + vowelCount);
System.out.println("Line count: " + lineCount);
System.out.println("Word count: " + wordCount);
System.out.print("Average word count per line: "+avgWordCountPerLine);
}
public static int checkWordCount(String fileContent) {
// split words by puncutation and whitespace
String words[] = fileContent.split("[\\n .,;:&?]"); // array of words
String punctutations = ".,:;";
boolean isPunctuation = false;
int wordCount = 0;
// for every word in the word array
for (String word : words) {
// only check if it's a word if the word isn't whitespace
if (!word.trim().isEmpty()) {
// for every punctuation
for (char punctuation : punctutations.toCharArray()) {
// if the trimmed word is just a punctuation
if (word.trim().equals(String.valueOf(punctuation)))
{
isPunctuation = true;
}
}
// only add one to wordCount if the word wasn't punctuation
if (!isPunctuation) {
wordCount++;
}
}
}
return wordCount;
}
}
示例输入/输出:
文件:
This is a test. How do you do?
This is still a test.Let's go,,count.
输出:
This is a test. How do you do?
This is still a test.Let's go,,count.
--------------------------------
Vowel count: 18
Line count: 4
Word count: 16
Average word count per line: 4.0
关于java - 在 Java 中读取文本文件时进行跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21246006/