java识别一篇文章中某单词出现个数的方法
本文实例讲述了java识别一篇文章中某单词出现个数的方法。分享给大家供大家参考。具体如下:
1.java代码:
importjava.io.DataInputStream; importjava.io.FileInputStream; importjava.io.FileNotFoundException; importjava.io.IOException; importjava.util.StringTokenizer; importjava.util.regex.Matcher; importjava.util.regex.Pattern; publicclassSelect{ publicstaticvoidmain(String[]args){ intnum=0; //定义:字节读取流 FileInputStreamfis; try{ //此处的路径需要根据具体情况来进行修改 fis=newFileInputStream("H:\\TankWar1.9\\src\\Tank.java"); DataInputStreamdis=newDataInputStream(fis); Stringline=null; while((line=dis.readLine())!=null){ //创建字符解析器 StringTokenizerst=newStringTokenizer(line,"!&(){}+-=':;<>/"); while(st.hasMoreTokens()){ Stringstring=st.nextToken(); if(string.equals("if")){num++;}} ; } }catch(FileNotFoundExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } System.out.println(num); } }
2.Select.java:
importjava.io.DataInputStream; importjava.io.FileInputStream; importjava.io.FileNotFoundException; importjava.io.IOException; importjava.util.StringTokenizer; importjava.util.regex.Matcher; importjava.util.regex.Pattern; publicclassSelect{ publicstaticvoidmain(String[]args){ intnum=0; //定义:字节读取流 FileInputStreamfis; try{ fis=newFileInputStream("H:\\TankWar1.9\\src\\Tank.java"); DataInputStreamdis=newDataInputStream(fis); Stringline=null; while((line=dis.readLine())!=null){ //创建字符解析类 StringTokenizerst=newStringTokenizer(line,"!&(){}+-=':;<>/"); while(st.hasMoreTokens()){ Stringstring=st.nextToken(); if(string.equals("if")){num++;}} ; } }catch(FileNotFoundExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } System.out.println(num); } }
3.StringTokenizerDemo.java:
importjava.util.*; publicclassStringTokenizerDemo { publicstaticvoidmain(String[]args) { Stringstr1="Helloworld!ThisisJavacode,stringTokenizerDemo."; //声明并初始化字符串str1 Stringstr2="HowtouseStringTokenizer?StringTokenizer?"; //声明并初始化字符串str2 StringTokenizerstrT1=newStringTokenizer(str1,",.!"); //创建StringTokenizer类的对象strT1,并构造字符串str1的分析器 //以空格符、","、"."及"!"作为定界符 StringTokenizerstrT2=newStringTokenizer(str2,"?"); //创建StringTokenizer类的对象strT2,并构造字符串str2的分析器 //以空格符及"?"作为定界符 intnum1=strT1.countTokens(); //获取字符串str1中语言符号的个数 intnum2=strT2.countTokens(); //获取字符串str2中语言符号的个数 System.out.println("str1has"+num1+"words.Theyare:"); while(strT1.hasMoreTokens()) {//利用循环来获取字符串str1中下一个语言符号,并输出 Stringstr=strT1.nextToken(); System.out.print("\""+str+"\""); } System.out.println("\nstr2has"+num2+"words.Theyare:"); while(strT2.hasMoreTokens()) {//利用循环来获取字符串str2中下一个语言符号,并输出 Stringstr=strT2.nextToken(); System.out.print("\""+str+"\""); } } }
希望本文所述对大家的java程序设计有所帮助。