基于最大正向匹配算法的中文分词

package test.testAi;

import java.util.ArrayList;
import java.util.List;

public class Test01 {
    public static void main(String[] args) {
        String[] words = new String[]{"我们","明天","去","郊游","打篮球","喝","风华正茂","书生意气"};
        String message = "你好,明天天气怎样?适合打篮球吗?";
        System.out.println(cut(message,words));
    }

    /**
     * 分词功能 基于最大正向匹配算法
     * @param message
     */
    public static List<String > cut(String message,String[] words) {
        int maxWordLength = getMaxWordLength(words);
        List<String > cutResult = new ArrayList<String>();
        while (message.length() > 0) {
            String matchMessage = message.substring(0, maxWordLength>message.length()?message.length():maxWordLength);
            while (!strsContain(words,matchMessage)) {
                if (matchMessage.length() > 1) {
                    matchMessage = matchMessage.substring(0, matchMessage.length() - 1);
                } else{
                    break;
                }
            }
            cutResult.add(matchMessage);
            message = message.substring(matchMessage.length());
        }
        return cutResult;
    }

    public static boolean strsContain(String[] strs,String str){
        for(String st:strs){
            if(st.equals(str)){
                return true;
            }
        }
        return false;
    }

    public static int getMaxWordLength(String[] strs){
        int maxWordLength = strs[0].length();
        for (int i = 0; i <strs.length ; i++) {
            if(maxWordLength<strs[i].length()){
                maxWordLength = strs[i].length();
            }
        }
        return maxWordLength;
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值