java关键词组匹配算法

5 篇文章 0 订阅

首先我们将对代码进行基础构思:

一、 创建TrieNode 类

Trie 树的节点类,用于构建 Trie 树。TrieNode 类有以下成员变量:
children:一个 Map,用于存储当前节点的子节点,key 是字符,value 是对应的子节点 TrieNode。
isEndOfWord:布尔值,表示当前节点是否是一个关键词的结尾。
fail:失败指针,指向其他节点,用于构建 Trie 树的失败指针。
matchedKeywords:一个 Set,用于存储匹配到的关键词。

/**
 * Trie树节点类
 */
class TrieNode {
    Map<Character, TrieNode> children; // 子节点映射表
    boolean isEndOfWord; // 是否是关键词结尾
    TrieNode fail; // 失败指针,指向其他节点
    Set<String> matchedKeywords; // 匹配到的关键词集合

    public TrieNode() {
        children = new HashMap<>();
        isEndOfWord = false;
        fail = null;
        matchedKeywords = new HashSet<>();
    }
}

二 、创建Trie 类

Trie 类用于构建 Trie 树,并实现相关功能。Trie 类有以下成员变量:
root:Trie 树的根节点。
Trie 类有以下成员方法:
insert(String word): 将一个关键词插入到 Trie 树中。在插入过程中,逐个字符遍历,如果当前字符不存在对应的子节点,则创建一个新的节点并插入;如果当前字符已存在对应的子节点,则直接获取子节点继续遍历。最后标记当前节点为关键词结尾,并将该关键词添加到节点的 matchedKeywords 集合中。
buildFailPointers():构建 Trie 树的失败指针。通过 BFS 遍历 Trie 树,为每个节点设置失败指针,使得在搜索过程中可以快速回溯失败节点,从而实现 KMP 算法的功能。同时,也将匹配到的关键词集合合并到当前节点的 matchedKeywords 中。
search(String text):在文本中搜索关键词。根据 Trie 树,逐个字符遍历文本,并根据失败指针快速回溯,找到匹配的关键词。

/**
 * Trie树类
 */
class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }
    

    /**
     * 插入关键词到Trie树
     * @param word
     */
    public void insert(String word) {
        TrieNode current = root;
        for (char ch : word.toCharArray()) {
            current.children.putIfAbsent(ch, new TrieNode());
            current = current.children.get(ch);
        }
        current.isEndOfWord = true;
        current.matchedKeywords.add(word);
    }
    

    /**
     * 构建Trie树的失败指针,用于KMP算法
     */
    public void buildFailPointers() {
        Queue<TrieNode> queue = new LinkedList<>();
        for (TrieNode child : root.children.values()) {
            child.fail = root;
            queue.add(child);
        }

        while (!queue.isEmpty()) {
            TrieNode current = queue.poll();
            for (Map.Entry<Character, TrieNode> entry : current.children.entrySet()) {
                char ch = entry.getKey();
                TrieNode child = entry.getValue();

                TrieNode failNode = current.fail;
                while (failNode != null && !failNode.children.containsKey(ch)) {
                    failNode = failNode.fail;
                }

                if (failNode == null) {
                    child.fail = root;
                } else {
                    child.fail = failNode.children.get(ch);
                    child.matchedKeywords.addAll(child.fail.matchedKeywords); // 合并匹配关键词集合
                }

                queue.add(child);
            }
        }
    }

三. 创建ChineseKeywordMatcher 类

ChineseKeywordMatcher 类是程序的入口点,负责读取用户输入的文本,并进行匹配。
ChineseKeywordMatcher 类有以下成员方法:
在主方法main中,我们定义了多组关键词,构建 Trie 树并插入关键词,然后构建失败指针,接着获取用户输入的文本,最后通过并行计算搜索组合关键词,并输出匹配的结果。
searchCombinationsParallel(String text, List<List> keywordGroups):并行计算搜索组合关键词,并返回匹配的组合关键词集合。在这个方法中,我们使用线程池来同时搜索多组关键词,从而提高搜索效率。
generateCombinations(String text, List keywords, StringBuilder currentCombination, Set matchedKeywords):生成所有组合关键词,并在文本中查找匹配。这是一个辅助方法,在主方法中调用,并通过非递归方式生成组合关键词,然后根据 Trie 树在文本中查找匹配。

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 定义多组关键词
        List<List<String>> keywordGroups = new ArrayList<>();
        keywordGroups.add(Arrays.asList("人工智能", "AI"));
        keywordGroups.add(Arrays.asList("隐私计算", "联邦学习", "可信执行环境"));

        // 创建Trie树并插入关键词
        Trie trie = new Trie();
        for (List<String> keywords : keywordGroups) {
            for (String keyword : keywords) {
                trie.insert(keyword);
            }
        }

        // 构建Trie树的失败指针,用于KMP算法
        trie.buildFailPointers();

        // 获取用户输入的文本
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入中文文本:");
        String userInput = scanner.nextLine();
        scanner.close();

        // 并行计算搜索组合关键词,并返回匹配的组合关键词集合
        Set<String> matchedCombinationKeywords = searchCombinationsParallel(userInput, keywordGroups);

        if (!matchedCombinationKeywords.isEmpty()) {
            System.out.println("匹配的组合关键词:");
            for (String keyword : matchedCombinationKeywords) {
                System.out.println(keyword);
            }
        } else {
            System.out.println("没有匹配到组合关键词。");
        }
    }

四、 输入文本

在代码的 main 方法中,通过 Scanner 读取用户输入的中文文本。

  // 获取用户输入的文本
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入中文文本:");
        String userInput = scanner.nextLine();
        scanner.close();

注意:这里有部分长字符串需要剔除空格才可以精准匹配

五、 匹配组合关键词

在 searchCombinationsParallel 方法中,我们使用线程池和并行计算来搜索多组关键词的组合关键词。在 generateCombinations 方法中,我们通过非递归方式生成组合关键词,并利用 Trie 树在文本中查找匹配。最终输出匹配到的组合关键词。

  /**
     * 并行计算:在文本中搜索组合关键词,并返回匹配的组合关键词集合
     * @param text
     * @param keywordGroups
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public static Set<String> searchCombinationsParallel(String text, List<List<String>> keywordGroups) throws InterruptedException, ExecutionException {
        // 获取可用处理器核心数,并创建对应数量的线程池
        int numThreads = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(numThreads);

        // 使用线程安全的集合来保存匹配结果
        Set<String> matchedCombinationKeywords = new ConcurrentSkipListSet<>();

        // 创建并行任务列表
        List<Callable<Set<String>>> tasks = new ArrayList<>();
        for (List<String> keywords : keywordGroups) {
            tasks.add(() -> {
                Set<String> matchedKeywords = new HashSet<>();
                generateCombinations(text, keywords, new StringBuilder(), matchedKeywords);
                return matchedKeywords;
            });
        }

        // 并行执行任务,获取结果并合并到结果集合
        List<Future<Set<String>>> futures = executorService.invokeAll(tasks);
        for (Future<Set<String>> future : futures) {
            matchedCombinationKeywords.addAll(future.get());
        }

        // 关闭线程池
        executorService.shutdown();

        return matchedCombinationKeywords;
    }


    /**
     * 生成所有组合关键词,并在文本中查找匹配
     * @param text
     * @param keywords
     * @param currentCombination
     * @param matchedKeywords
     */
    private static void generateCombinations(String text, List<String> keywords, StringBuilder currentCombination, Set<String> matchedKeywords) {
        int[] indices = new int[keywords.size()]; // 记录每组关键词的索引

        while (true) {
            StringBuilder currentCombinationKeyword = new StringBuilder();

            // 生成当前的组合关键词
            for (int i = 0; i < keywords.size(); i++) {
                String keyword = keywords.get(i);
               // int index = indices[i];
                if (currentCombinationKeyword.length() > 0) {
                    currentCombinationKeyword.append(",");
                }
                currentCombinationKeyword.append(keyword);
                indices[i]++;
            }

            Trie trie = new Trie();
            for (String keyword : currentCombinationKeyword.toString().split(",")) {
                trie.insert(keyword);
            }
            trie.buildFailPointers();

            Set<String> matched = trie.search(text);
            if (!matched.isEmpty()) {
                matchedKeywords.addAll(matched);
            }

            // 移动索引,类似组合数学中的组合生成算法
            int j = keywords.size() - 1;
            while (j >= 0 && indices[j] == keywords.size()) {
                indices[j] = 0;
                j--;
            }
            if (j < 0) {
                break;
            }
        }
    }

根据以上步骤思路我们编写完整代码,具体完整代码如下所示:

package cn.konne.konneim.download;
import java.util.*;
import java.util.concurrent.*;


/**
 * Trie树节点类
 */
class TrieNode {
    Map<Character, TrieNode> children; // 子节点映射表
    boolean isEndOfWord; // 是否是关键词结尾
    TrieNode fail; // 失败指针,指向其他节点
    Set<String> matchedKeywords; // 匹配到的关键词集合

    public TrieNode() {
        children = new HashMap<>();
        isEndOfWord = false;
        fail = null;
        matchedKeywords = new HashSet<>();
    }
}


/**
 * Trie树类
 */
class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }
    

    /**
     * 插入关键词到Trie树
     * @param word
     */
    public void insert(String word) {
        TrieNode current = root;
        for (char ch : word.toCharArray()) {
            current.children.putIfAbsent(ch, new TrieNode());
            current = current.children.get(ch);
        }
        current.isEndOfWord = true;
        current.matchedKeywords.add(word);
    }
    

    /**
     * 构建Trie树的失败指针,用于KMP算法
     */
    public void buildFailPointers() {
        Queue<TrieNode> queue = new LinkedList<>();
        for (TrieNode child : root.children.values()) {
            child.fail = root;
            queue.add(child);
        }

        while (!queue.isEmpty()) {
            TrieNode current = queue.poll();
            for (Map.Entry<Character, TrieNode> entry : current.children.entrySet()) {
                char ch = entry.getKey();
                TrieNode child = entry.getValue();

                TrieNode failNode = current.fail;
                while (failNode != null && !failNode.children.containsKey(ch)) {
                    failNode = failNode.fail;
                }

                if (failNode == null) {
                    child.fail = root;
                } else {
                    child.fail = failNode.children.get(ch);
                    child.matchedKeywords.addAll(child.fail.matchedKeywords); // 合并匹配关键词集合
                }

                queue.add(child);
            }
        }
    }
    

    /**
     * 在文本中搜索关键词,并返回匹配的关键词集合
     * @param text 要匹配得文本串
     * @return
     */
    public Set<String> search(String text) {
        TrieNode current = root;
        Set<String> matchedKeywords = new HashSet<>();
        StringBuilder matchedKeyword = new StringBuilder();

        for (char ch : text.toCharArray()) {
            while (current != root && !current.children.containsKey(ch)) {
                current = current.fail;
            }

            if (current.children.containsKey(ch)) {
                current = current.children.get(ch);
                matchedKeyword.append(ch);
                if (current.isEndOfWord) {
                    matchedKeywords.addAll(current.matchedKeywords);
                }
            } else {
                current = root;
                matchedKeyword.setLength(0);
            }
        }

        return matchedKeywords;
    }
}

public class ChineseKeywordMatcher {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 定义多组关键词
        List<List<String>> keywordGroups = new ArrayList<>();
        keywordGroups.add(Arrays.asList("人工智能", "AI"));
        keywordGroups.add(Arrays.asList("隐私计算", "联邦学习", "可信执行环境"));

        // 创建Trie树并插入关键词
        Trie trie = new Trie();
        for (List<String> keywords : keywordGroups) {
            for (String keyword : keywords) {
                trie.insert(keyword);
            }
        }

        // 构建Trie树的失败指针,用于KMP算法
        trie.buildFailPointers();

        // 获取用户输入的文本
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入中文文本:");
        String userInput = scanner.nextLine();
        scanner.close();

        // 并行计算搜索组合关键词,并返回匹配的组合关键词集合
        Set<String> matchedCombinationKeywords = searchCombinationsParallel(userInput, keywordGroups);

        if (!matchedCombinationKeywords.isEmpty()) {
            System.out.println("匹配的组合关键词:");
            for (String keyword : matchedCombinationKeywords) {
                System.out.println(keyword);
            }
        } else {
            System.out.println("没有匹配到组合关键词。");
        }
    }


    /**
     * 并行计算:在文本中搜索组合关键词,并返回匹配的组合关键词集合
     * @param text
     * @param keywordGroups
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public static Set<String> searchCombinationsParallel(String text, List<List<String>> keywordGroups) throws InterruptedException, ExecutionException {
        // 获取可用处理器核心数,并创建对应数量的线程池
        int numThreads = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(numThreads);

        // 使用线程安全的集合来保存匹配结果
        Set<String> matchedCombinationKeywords = new ConcurrentSkipListSet<>();

        // 创建并行任务列表
        List<Callable<Set<String>>> tasks = new ArrayList<>();
        for (List<String> keywords : keywordGroups) {
            tasks.add(() -> {
                Set<String> matchedKeywords = new HashSet<>();
                generateCombinations(text, keywords, new StringBuilder(), matchedKeywords);
                return matchedKeywords;
            });
        }

        // 并行执行任务,获取结果并合并到结果集合
        List<Future<Set<String>>> futures = executorService.invokeAll(tasks);
        for (Future<Set<String>> future : futures) {
            matchedCombinationKeywords.addAll(future.get());
        }

        // 关闭线程池
        executorService.shutdown();

        return matchedCombinationKeywords;
    }
    

    /**
     * 生成所有组合关键词,并在文本中查找匹配 
     * @param text
     * @param keywords
     * @param currentCombination
     * @param matchedKeywords
     */
    private static void generateCombinations(String text, List<String> keywords, StringBuilder currentCombination, Set<String> matchedKeywords) {
        int[] indices = new int[keywords.size()]; // 记录每组关键词的索引

        while (true) {
            StringBuilder currentCombinationKeyword = new StringBuilder();

            // 生成当前的组合关键词
            for (int i = 0; i < keywords.size(); i++) {
                String keyword = keywords.get(i);
               // int index = indices[i];
                if (currentCombinationKeyword.length() > 0) {
                    currentCombinationKeyword.append(",");
                }
                currentCombinationKeyword.append(keyword);
                indices[i]++;
            }

            Trie trie = new Trie();
            for (String keyword : currentCombinationKeyword.toString().split(",")) {
                trie.insert(keyword);
            }
            trie.buildFailPointers();

            Set<String> matched = trie.search(text);
            if (!matched.isEmpty()) {
                matchedKeywords.addAll(matched);
            }

            // 移动索引,类似组合数学中的组合生成算法
            int j = keywords.size() - 1;
            while (j >= 0 && indices[j] == keywords.size()) {
                indices[j] = 0;
                j--;
            }
            if (j < 0) {
                break;
            }
        }
    }
}


以上为java关键词组匹配程序,如果有啥不足欢迎支持

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hello.Reader

请我喝杯咖啡吧😊

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值