Java作业整理 敏感词汇
1. 敏感词汇分析(难)
要求:任意选择一个文本文件,分析该文件,如果存在敏感词汇(这些词汇保存在sentive.txt文件中,每个词占一行),报告每个词出现的次数。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public class sensitive_Vocabulary {
Scanner input=new Scanner(System.in);
public String[] ch;
public void write(int number) throws Exception{
System.out.println("请输入你的敏感词汇:");
ObjectOutputStream output =
new ObjectOutputStream(new FileOutputStream("sensitive.txt"));
for(int i = 0; i < number;i++){
String str = input.nextLine();
output.writeUTF(str);
}
output.close();
}
public void readObject(int number) throws Exception{
ObjectInputStream input =
new ObjectInputStream(new FileInputStream("sensitive.txt"));
ch = new String[number];
for(int j = 0; j < number; j++){
ch[j] = input.readUTF();
// System.out.println("敏感词汇为:"+ch[j]);
}
input.close();
}
}
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class read_File {
public static void main(String[] args) throws Exception {
Scanner input=new Scanner(System.in);
System.out.println("请输入你所要输入的敏感词汇个数:");
int number=input.nextInt();
int[] array=new int[number];
for(int r=0;r<number;r++)
array[r]=0;
sensitive_Vocabulary test=new sensitive_Vocabulary();
test.write(number);
test.readObject(number);
try {
StringBuffer sb= new StringBuffer("");
FileReader reader = new FileReader("G://test.txt");
BufferedReader br = new BufferedReader(reader);
String str = null;
String str_fir;
while((str = br.readLine()) != null){
sb.append(str+"\n");
for(int k=0;k<number;k++){
str_fir=" "+test.ch[k]+" ";
array[k] += countStr(str,str_fir);
// System.out.println(array[k] +" " +str+"\n"+test.ch[k]);
}
}
br.close();
reader.close();
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
for(int j=0;j<number;j++)
System.out.println("敏感词"+" "+test.ch[j]+" " +"有"+array[j]
+"个");
}
public static int countStr(String str1, String str2){
int counter=0;
if (str1.indexOf(str2) == -1){
return 0;
}
while(str1.indexOf(str2)!=-1){
counter++;
str1=str1.substring(str1.indexOf(str2)+str2.length());
}
return counter;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理