java写的分词小程序

 

根据给出的正则式,构建分词程序,完成相应的分词任务,并返回所有单词以及单词类别。

<关键字>-> int |for| while | do | return | break | continue

<运算符>->   + | - | * | / |==| < | <= |!= | > | >=

<界符>-> , | ; | ( | ) | {|}

<标识符>-> letter (letter | digit)*

<整型常数>-> digit digit*

<小数>-> digit digit* . digit digit*

 

程序说明(关键代码)

 

public void getFenCi() throws Exception {   

        BufferedReader br = new BufferedReader(new InputStreamReader(

                new FileInputStream(filePath)));

        //遍历每一行

        for (String line =br.readLine(); line != null; line = br.readLine()) {

          String[] s1 = line.trim().split(" ");//得到空格分开的字符串数组并且去掉首尾空格          

 for(int i=0;i<s1.length;i++){

 char[] CharArray= s1[i].toCharArray();

       for(char c : CharArray) {

      if(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {//字母

                if (match_4 == 1) {//之前是运算符

                    matchEqual_4();//str设置为运算符

                }

                if (match_3 == 1) {//之前是整数

                    matchEqual_3();

                }

                str1 = str1 + c;

                match_1 = 1;

            } else if (match_4(c + "")) {//分隔符

                if(match_1 == 1){

                    matchEqual_1();

                }

                if (match_4 == 1) {

                    matchEqual_4();

                }

                if (match_3 == 1) {

                    matchEqual_3();

                }

                str1 = "";

                str1 = str1 + c;

                setValue("5", str1);

                str1 = "";

            } else if (match_2(c + "")) {//标识符

                if(match_1 == 1){

                    matchEqual_1();

                }

                if (match_3 == 1) {

                    matchEqual_3();

                }

                str1 = str1 + c;

                match_4 = 1;

            } else if (match_3(c + "")) {//数字匹配

                if(match_1==1){

                    matchEqual_1();

                }

                if (match_4 == 1) {

                    matchEqual_4();

                }

                str1 = str1 + c;

                match_3 = 1;

            }

}

    }

        }

        br.close();

}

 

思路总结

 

1程序主要利用str存储每一个分词,根据当前字符和前一个分词判断出是继续添加字符进分词,还是结束添加,并判断出分词类型,存储。最后通过map存储分词和类型。

2正则式只是实现一部分,但是小数都没有实现,离真正分词程序有很大不同。

3空格是默认的分隔符,每一行也应该是分隔的。因此用readline方法。并且通过line.trim().split(" ")得到空格分开的字符串数组并且去掉首尾空格。     

 

posted @ 2017-04-20 22:23  守夜之人  阅读(921)  评论(0编辑  收藏  举报