java识别一篇文章中某单词出现个数 java识别一篇文章中某单词出现个数的方法
张庚 人气:0想了解java识别一篇文章中某单词出现个数的方法的相关内容吗,张庚在本文为您仔细讲解java识别一篇文章中某单词出现个数的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java,识别,文章,单词出现个数,下面大家一起来学习吧。
本文实例讲述了java识别一篇文章中某单词出现个数的方法。分享给大家供大家参考。具体如下:
1. java代码:
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Select { public static void main(String[] args) { int num = 0; //定义:字节读取流 FileInputStream fis; try { //此处的路径需要根据具体情况来进行修改 fis = new FileInputStream("H:\\TankWar1.9\\src\\Tank.java"); DataInputStream dis = new DataInputStream(fis); String line = null; while ((line = dis.readLine()) != null) { //创建字符解析器 StringTokenizer st=new StringTokenizer(line,"!&(){}+-= ':;<> /"); while(st.hasMoreTokens()) { String string=st.nextToken(); if(string.equals("if")) { num++; } } ; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(num); } }
2. Select.java:
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Select { public static void main(String[] args) { int num = 0; //定义:字节读取流 FileInputStream fis; try { fis = new FileInputStream("H:\\TankWar1.9\\src\\Tank.java"); DataInputStream dis = new DataInputStream(fis); String line = null; while ((line = dis.readLine()) != null) { //创建字符解析类 StringTokenizer st=new StringTokenizer(line,"!&(){}+-= ':;<> /"); while(st.hasMoreTokens()) { String string=st.nextToken(); if(string.equals("if")) { num++; } } ; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(num); } }
3. StringTokenizerDemo.java:
import java.util.*; public class StringTokenizerDemo { public static void main(String[] args) { String str1 = "Hello world!This is Java code,stringTokenizer Demo."; //声明并初始化字符串str1 String str2 = "How to use StringTokenizer?StringTokenizer?"; //声明并初始化字符串str2 StringTokenizer strT1 = new StringTokenizer(str1," ,.!"); //创建StringTokenizer类的对象strT1,并构造字符串str1的分析器 //以空格符、","、"."及"!"作为定界符 StringTokenizer strT2 = new StringTokenizer(str2," ?"); //创建StringTokenizer类的对象strT2,并构造字符串str2的分析器 //以空格符及"?"作为定界符 int num1 = strT1.countTokens(); //获取字符串str1中语言符号的个数 int num2 = strT2.countTokens(); //获取字符串str2中语言符号的个数 System.out.println("str1 has "+num1+" words.They are:"); while(strT1.hasMoreTokens()) { //利用循环来获取字符串str1中下一个语言符号,并输出 String str = strT1.nextToken(); System.out.print("\""+str+"\" "); } System.out.println("\nstr2 has "+num2+" words.They are:"); while(strT2.hasMoreTokens()) { //利用循环来获取字符串str2中下一个语言符号,并输出 String str = strT2.nextToken(); System.out.print("\""+str+"\" "); } } }
希望本文所述对大家的java程序设计有所帮助。
加载全部内容