查券返利机器人自然语言查询解析:关键词提取与意图匹配的轻量级实现
大家好,我是 微赚淘客系统3.0 的研发者省赚客!
在微信或私域群聊中,用户常以自然语言形式发送商品需求,如“帮我找一下 iPhone 16 的优惠券”、“有没有耐克跑鞋的返利?”等。为避免依赖大模型带来的高成本与延迟,微赚淘客系统3.0 采用基于规则+词典的轻量级 NLU 方案,实现在毫秒级内完成关键词提取与意图识别,支撑日均百万级查询。
一、核心流程设计
整个解析流程分为三步:
- 文本预处理:清洗、分词、去除停用词;
- 关键词提取:识别商品名、品牌、型号等实体;
- 意图匹配:判断是否为查券请求,并提取结构化参数。
系统不依赖外部 NLP 服务,全部逻辑内置于 Java 后端。
二、自定义分词与词典加载
我们使用正向最大匹配(FMM)算法实现中文分词,结合自建商品词典提升准确率。
packagejuwatech.cn.nlp.segment;importjava.util.*;publicclassSimpleSegmenter{privatefinalSet<String>dict;privatefinalSet<String>stopWords;privatefinalintmaxLen;publicSimpleSegmenter(Set<String>dict,Set<String>stopWords){this.dict=dict;this.stopWords=stopWords;this.maxLen=dict.stream().mapToInt(String::length).max().orElse(10);}publicList<String>segment(Stringtext){List<String>tokens=newArrayList<>();inti=0;while(i<text.length()){intmatchedLen=1;for(intlen=Math.min(maxLen,text.length()-i);len>=1;len--){Stringword=text.substring(i,i+len);if(dict.contains(word)){matchedLen=len;break;}}Stringtoken=text.substring(i,i+matchedLen);if(!stopWords.contains(token)){tokens.add(token);}i+=matchedLen;}returntokens;}}词典通过 Spring 初始化加载:
packagejuwatech.cn.nlp.config;importjuwatech.cn.nlp.segment.SimpleSegmenter;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.nio.charset.StandardCharsets;importjava.util.HashSet;importjava.util.Set;@ConfigurationpublicclassNlpConfig{@BeanpublicSimpleSegmentersegmenter()throwsIOException{Set<String>dict=loadLines("nlp/product_dict.txt");Set<String>stopWords=loadLines("nlp/stopwords.txt");returnnewSimpleSegmenter(dict,stopWords);}privateSet<String>loadLines(Stringpath)throwsIOException{try(InputStreamis=getClass().getClassLoader().getResourceAsStream(path);BufferedReaderreader=newBufferedReader(newInputStreamReader(is,StandardCharsets.UTF_8))){returnreader.lines().collect(HashSet::new,HashSet::add,HashSet::addAll);}}}product_dict.txt示例内容:
iPhone 16 耐克 阿迪达斯 华为 Mate 60 小米 14 运动鞋 蓝牙耳机三、意图识别与参数抽取
定义查询意图模型:
packagejuwatech.cn.nlp.model;publicclassUserQueryIntent{privatebooleanisCouponRequest;// 是否查券意图privateStringkeyword;// 提取的商品关键词privateStringbrand;// 品牌(可选)privateStringcategory;// 类目(如“手机”、“鞋子”)// getters & setters}意图匹配器实现:
packagejuwatech.cn.nlp.intent;importjuwatech.cn.nlp.model.UserQueryIntent;importjuwatech.cn.nlp.segment.SimpleSegmenter;importorg.springframework.stereotype.Component;importjava.util.Arrays;importjava.util.List;importjava.util.Set;importjava.util.stream.Collectors;@ComponentpublicclassCouponIntentMatcher{privatestaticfinalSet<String>TRIGGER_WORDS=Set.of("优惠券","券","返利","查券","领券","有券吗");privatestaticfinalSet<String>BRANDS=Set.of("苹果","华为","小米","耐克","阿迪达斯");privatestaticfinalSet<String>CATEGORIES=Set.of("手机","耳机","跑鞋","运动鞋","平板");privatefinalSimpleSegmentersegmenter;publicCouponIntentMatcher(SimpleSegmentersegmenter){this.segmenter=segmenter;}publicUserQueryIntentparse(Stringinput){StringcleanInput=input.replaceAll("[^\\p{L}\\p{N}\\s]","").toLowerCase();List<String>tokens=segmenter.segment(cleanInput);booleanhasTrigger=tokens.stream().anyMatch(TRIGGER_WORDS::contains);if(!hasTrigger&&!cleanInput.contains("找")&&!cleanInput.contains("有没有")){returnnewUserQueryIntent();// 非查券意图}UserQueryIntentintent=newUserQueryIntent();intent.setIsCouponRequest(true);// 提取品牌StringfoundBrand=tokens.stream().filter(BRANDS::contains).findFirst().orElse(null);intent.setBrand(foundBrand);// 提取类目StringfoundCategory=tokens.stream().filter(CATEGORIES::contains).findFirst().orElse(null);intent.setCategory(foundCategory);// 关键词:优先使用最长匹配的商品词List<String>productTokens=tokens.stream().filter(token->token.length()>1).sorted((a,b)->Integer.compare(b.length(),a.length()))// 长词优先.collect(Collectors.toList());if(!productTokens.isEmpty()){intent.setKeyword(String.join(" ",productTokens));}else{// 回退到原始输入中的非触发词部分Stringfallback=Arrays.stream(cleanInput.split("\\s+")).filter(w->!TRIGGER_WORDS.contains(w)).collect(Collectors.joining(" "));intent.setKeyword(fallback.trim());}returnintent;}}四、集成到消息处理入口
在微信消息处理器中调用:
packagejuwatech.cn.bot.handler;importjuwatech.cn.nlp.intent.CouponIntentMatcher;importjuwatech.cn.nlp.model.UserQueryIntent;importjuwatech.cn.service.CouponSearchService;importorg.springframework.stereotype.Service;@ServicepublicclassWechatMessageHandler{privatefinalCouponIntentMatcherintentMatcher;privatefinalCouponSearchServicecouponSearchService;publicWechatMessageHandler(CouponIntentMatcherintentMatcher,CouponSearchServicecouponSearchService){this.intentMatcher=intentMatcher;this.couponSearchService=couponSearchService;}publicStringhandleTextMessage(StringfromUser,Stringcontent){UserQueryIntentintent=intentMatcher.parse(content);if(!intent.isCouponRequest()){return"您好,请发送商品名称或链接,例如“iPhone 16 优惠券”";}if(intent.getKeyword()==null||intent.getKeyword().isEmpty()){return"未识别到有效商品信息,请重试";}Stringresult=couponSearchService.searchCoupons(intent.getKeyword());returnresult!=null?result:"暂未找到相关优惠券,换个说法试试?";}}五、性能与准确率优化
- 分词词典按热度排序,高频词前置提升匹配速度;
- 支持模糊匹配:如“苹果16” → “iPhone 16”;
- 日志埋点记录未命中查询,用于迭代词典。
该方案在 4 核 8G 服务器上可支撑 500+ QPS,平均响应时间 < 15ms,准确率达 92%(基于内部测试集)。
本文著作权归 微赚淘客系统3.0 研发团队,转载请注明出处!