计算文件中的单词数

时间:2010-11-04 05:29:23

标签: java algorithm loops io

我在计算文件中的单词数时遇到问题。我正在采取的方法是,当我看到空格或新线时,我知道要算一个字。

问题在于,如果段落之间有多行,那么我最终也将它们视为单词。如果你看一下readFile()方法,你就可以看到我在做什么。

你能帮助我并指导我如何解决这个问题吗?

示例输入文件(包括空行):

word word word
word word

word word word

14 个答案:

答案 0 :(得分:11)

您可以使用带有FileInputStream的Scanner而不是带有FileReader的BufferedReader。例如: -

File file = new File("sample.txt");
try(Scanner sc = new Scanner(new FileInputStream(file))){
    int count=0;
    while(sc.hasNext()){
        sc.next();
        count++;
    }
System.out.println("Number of words: " + count);
}

答案 1 :(得分:10)

我会改变你的方法。首先,我将使用BufferedReader使用readLine()逐行读取文件文件。然后使用String.split("\\s")在空白上拆分每一行,并使用结果数组的大小来查看该行上有多少个单词。要获得字符数,您可以查看每行或每个拆分字的大小(取决于您是否要将空格计为字符)。

答案 2 :(得分:4)

这只是一个想法。有一种非常简单的方法可以做到这一点。如果您只需要多个单词而不是实际单词,那么只需使用Apache WordUtils

即可
import org.apache.commons.lang.WordUtils;

public class CountWord {

public static void main(String[] args) {    
String str = "Just keep a boolean flag around that lets you know if the previous character was whitespace or not pseudocode follows";

    String initials = WordUtils.initials(str);

    System.out.println(initials);
    //so number of words in your file will be
    System.out.println(initials.length());    
  }
}

答案 3 :(得分:3)

只需保留一个布尔标志即可让您知道前一个字符是否为空格(伪代码如下):

boolean prevWhitespace = false;
int wordCount = 0;
while (char ch = getNextChar(input)) {
  if (isWhitespace(ch)) {
    if (!prevWhitespace) {
      prevWhitespace = true;
      wordCount++;
    }
  } else {
    prevWhitespace = false;
  }
}

答案 4 :(得分:3)

import java.io.BufferedReader;
import java.io.FileReader;

public class CountWords {

    public static void main (String args[]) throws Exception {

       System.out.println ("Counting Words");       
       FileReader fr = new FileReader ("c:\\Customer1.txt");        
       BufferedReader br = new BufferedReader (fr);     
       String line = br.readLin ();
       int count = 0;
       while (line != null) {
          String []parts = line.split(" ");
          for( String w : parts)
          {
            count++;        
          }
          line = br.readLine();
       }         
       System.out.println(count);
    }
}

答案 5 :(得分:2)

黑客解决方案

您可以将文本文件读入String var。然后使用单个空格作为分隔符StringVar.Split(“”)将String拆分为数组。

数组计数等于文件中“字”的数量。 当然这不会给你一个行数。

答案 6 :(得分:2)

我认为正确的方法是通过Regex:

String fileContent = <text from file>;    
String[] words = Pattern.compile("\\s+").split(fileContent);
System.out.println("File has " + words.length + " words");

希望它有所帮助。 “\ s +”含义位于Pattern javadoc

答案 7 :(得分:0)

3个步骤:消耗所有空格,检查是否为一行,消耗所有非空白.3

while(true){
    c = inFile.read();                
    // consume whitespaces
    while(isspace(c)){ inFile.read() }
    if (c == '\n'){ numberLines++; continue; }
    while (!isspace(c)){
         numberChars++;
         c = inFile.read();
    }
    numberWords++;
}

答案 8 :(得分:0)

文件字数

如果在具有某些符号的单词之间,则可以拆分并计算单词数。

Scanner sc = new Scanner(new FileInputStream(new File("Input.txt")));
        int count = 0;
        while (sc.hasNext()) {

            String[] s = sc.next().split("d*[.@:=#-]"); 

            for (int i = 0; i < s.length; i++) {
                if (!s[i].isEmpty()){
                    System.out.println(s[i]);
                    count++;
                }   
            }           
        }
        System.out.println("Word-Count : "+count);

答案 9 :(得分:0)

在这里查看我的解决方案,它应该可行。我的想法是从单词中删除所有不需要的符号,然后将这些单词分开并将它们存储在其他变量中,我使用的是ArrayList。通过调整“excludedSymbols”变量,您可以添加更多要从单词中排除的符号。

select fr.*
from fixed_rates1 fr
order by date desc
limit 1;

答案 10 :(得分:0)

这可以通过Java 8实现:

Files.lines(Paths.get(file))
    .flatMap(str->Stream.of(str.split("[ ,.!?\r\n]")))
    .filter(s->s.length()>0).count();

答案 11 :(得分:0)

https

答案 12 :(得分:0)

以下代码支持Java 8

//将文件读入字符串

String fileContent=new String(Files.readAlBytes(Paths.get("MyFile.txt")),StandardCharacters.UFT_8);

//通过使用分隔符

分割将这些字符串保存到字符串列表中
List<String> words = Arrays.asList(contents.split("\\PL+"));

int count=0;
for(String x: words){
 if(x.length()>1) count++;
}

sop(x);

答案 13 :(得分:0)

如此简单,我们可以通过以下方法从文件中获取字符串:getText();

public class Main {

    static int countOfWords(String str) {
        if (str.equals("") || str == null) {
            return 0;
        }else{
            int numberWords = 0;
            for (char c : str.toCharArray()) {
                if (c == ' ') {
                    numberWords++;
                }
            }

            return ++numberWordss;
        }
    }
}
相关问题