Java作业整理 敏感词汇

来源:互联网 发布:javascript hide div 编辑:程序博客网 时间:2024/05/22 12:40

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;        }  }


0 0
原创粉丝点击