Java在文本文件中查找重复次数最多的单词
在此程序中,我们需要在给定的文本文件中查找出现次数最多的单词。这可以通过使用文件指针以读取模式打开文件来完成。逐行读取文件。一次拆分一行并存储在数组中。遍历数组,找到每个单词的频率,然后将频率与maxcount比较。如果频率大于maxcount,则将频率存储在maxcount中,并将相应的字存储在变量字中。该程序中使用的data.txt文件的内容如下所示。
data.txt
计算机程序是指令的集合,当由计算机执行时,指令将执行特定的任务。
计算机需要程序才能运行。
计算机程序通常是由计算机程序员以编程语言编写的。
计算机程序,库和相关软件的集合数据称为软件。
计算机程序可以按照功能类别进行分类,例如应用程序软件和系统软件。
算法
步骤1: START
步骤2: DEFINE String line, word = ""
步骤3: SET count = 0,maxCount = 0
步骤4: 定义
ArrayList words
步骤5: 使用文件读取器以读取模式打开文件。
步骤6: 从文件中读取行
步骤7: 通过循环,将每行转换为小写。
步骤8: 删除标点符号。
步骤9: 将行和行拆分为数组字符串[]。
步骤10: 将上一步中生成的所有单词添加到单词中。
步骤11: 设置i = 0。直到 i < words.size() 重复步骤12至步骤17
步骤12: SET count = 1
步骤13: 设置j = i + 1。重复步骤14至15,直到j < words.size()
步骤14: 如果是IF(words.get(i).equals(words.get(j))),然后count = count + 1。
步骤15: j = j + 1
步骤16: 如果IF计数> maxCount
,然后
maxCount = count
word = words.get(i)
步骤17: i = i + 1
步骤18: 打印单词
步骤19: END
程序:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class MostRepeatedWord {
public static void main(String[] args) throws Exception {
String line, word = "";
int count = 0, maxCount = 0;
ArrayList<
String>
words = new ArrayList<
String>
();
//Opens file in read mode
FileReader file = new FileReader("data.txt ");
BufferedReader br = new BufferedReader(file);
//Reads each line
while((line = br.readLine()) != null) {
String string[] = line.toLowerCase().split("([,.\\s]+) ");
//Adding all words generated in previous step into words
for(String s : string){
words.add(s);
}
}
//Determine the most repeated word in a file
for(int i = 0; i < words.size(); i++){
count = 1;
//Count each word in the file and store it in variable count
for(int j = i+1; j < words.size(); j++){
if(words.get(i).equals(words.get(j))){
count++;
}
}
//if maxCount is less than count then store value of count in maxCount
//and corresponding word to variable word
if(count > maxCount){
maxCount = count;
word = words.get(i);
}
}
System.out.println("Most repeated word: " + word);
br.close();
}
}
输出:
Most repeated word: computer