关键字检测匹配

关键字检测匹配

import ahocorasick def check_keyword(text, keywords): """检查文本中是否包含关键词""" A = ahocorasick.Automaton() for i, keyword in enumerate(keywords): A.add_word(keyword, (i, keyword)) A.make_automaton() matched_keywords = [] for end_index, (insert_order, keyword) in A.iter(text): if text[end_index-len(keyword)+1:end_index+1] == keyword: matched_keywords.append(keyword) if matched_keywords: matched_keywords.sort(key=lambda x: len(x), reverse=True) return True, matched_keywords[0] # 返回最长的匹配关键词 return False, None text = "你好有没有x350型号的车" keywords = [ "x350","x35","x3500","x3"] found, keyword = check_keyword(text, keywords) print(found, keyword)