我正在尝试制作一个程序来计算单词、行、句子的数量,以及文章“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/