Java教程

Java查找给定文本文件中的单词数

在此程序中,我们需要查找给定文本文件中出现次数最多的单词。这可以通过使用文件指针以读取模式打开文件来完成。逐行读取文件。一次拆分一行并存储在数组中。遍历数组并计数单词。程序中使用的data.txt文件的内容如下所示。
data.txt
计算机程序是指令的集合,当由计算机执行时,指令将执行特定的任务。
计算机需要程序才能运行。
计算机程序通常是由计算机程序员以编程语言编写的。
计算机程序,库和相关软件的集合数据称为软件。
计算机程序可以按照功能类别进行分类,例如应用程序软件和系统软件。

算法

步骤1: 开始 步骤2: DEFINE string = "characters" 步骤3: SET count = 0 步骤4: 使用文件读取器以读取模式打开文件。 第5步: 从文件中读取行 第6步: 直到文件末尾重复STEP 7至STEP 8 第7步: 将行拆分为单词,然后将其存储在数组string words[]。 步骤8: count = count + words.length 步骤9: 打印计数。 第10步: END

程序:

import java.io.BufferedReader;
import java.io.FileReader;
public class CountWordFile
{
    public static void main(String[] args) throws Exception {
        String line;
        int count = 0;
        //Opens a file in read mode
        FileReader file = new FileReader("data.txt ");
        BufferedReader br = new BufferedReader(file);
        //Gets each line till end of file is reached
        while((line = br.readLine()) != null) {
            //Splits each line into words
            String words[] = line.split("");
            //Counts each word
            count = count + words.length;
        }
        System.out.println("Number of words present in given file: " + count);
        br.close();
    }
}
输出:
Number of words present in given file: 63
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4