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
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: TextRank提取关键词算法是一种基于图模型的自动摘要和关键词抽取算法,它通过计算文本中的单词之间的相似度,将文本中的单词转化为图中的节点,并通过边的权重来表示单词之间的关系。然后通过PageRank等排序算法,计算每个单词的重要性,从而确定最具代表性的关键词。这种算法可以有效地自动提取出文本中最具代表性的关键词并生成文章摘要。 ### 回答2: 随着信息时代的爆发,我们所面临的信息量越来越庞大,而关键词提取就成为了解决信息溢出的关键。因此,Textrank提取关键词算法随之诞生。下面我会详细解释Textrank提取关键词算法是什么,它的原理以及它的应用。 Textrank提取关键词算法是一种基于图模型的文本关键词提取算法。它是利用文本中不同单词之间的相互关系,来计算每个词的权重得分。在这个算法中,每一个单词都是一种节点,节点之间的关系由边来表示。这些边表示单个单词与文本的其他部分的相关性,如句子、段落或文档等。 在Textrank提取关键词算法中,它使用了PageRank算法的一般思想,为节点赋予权重,这些权重反映了单词在文本中的重要性。Textrank计算每个节点的权重分数,度量这个节点对于整篇文本的重要性,并将每一个节点的权重分数排序,最终选择前面的单词作为关键词或短语。 Textrank提取关键词算法的原理是,首先将文本分成若干段,然后识别文本中的每一个单词,通过识别每个单词之间的关系,建立起图模型,然后采用PageRank算法来计算每个节点的权重,排序并输出权重最高的词作为文本的关键词顺序。 各种专业领域和社会应用,都将Textrank提取关键词算法作为信息检索技术,用于识别和抽取文本中的关键词或短语。如在搜索引擎中,Textrank算法被广泛应用以提取用户问题或提交内容的相关关键字。在新闻媒体中,Textrank算法可以用于快速浏览新闻摘要,以帮助读者快速找到文章的主题和背景。在科学研究领域中,Textrank算法通常用于简化领域术语和研究文献中的重要内容。 总之,Textrank提取关键词算法是一种用于标识文本中重要信息的有效方法。它使用基于图模型的算法,可以识别文本中的关键字、词和句子。这种算法在文本处理和信息检索方面具有广泛应用,是信息过滤和自动化分类的重要工具。 ### 回答3: 随着现代信息技术的快速发展,人们所需要处理的文本资料也随之增加。提取文本信息中的关键词是一种非常重要的文本分析技术。关键词不仅可以清晰地反映出文本信息的主题,还可以用于文本分类、文本聚类、信息检索和自然语言处理等多个领域。 目前,常用的文本关键词提取算法有很多,其中最知名的就属TF-IDF算法和TextRank算法。而相比于TF-IDF算法,TextRank算法更加全面、精确,并且能够解决TF-IDF算法中存在的一些“零元问题”。 TextRank算法是通过对词语之间的相似度进行计算,形成一张网状的图结构,并利用网状图的稳定性来进行关键词的提取。主要的运作原理就是循环迭代,每次都将每个节点更新一下权值。这样就能够让分数更精准的反映出一个节点的权重。 具体来说,TextRank算法通过以下几个步骤来实现关键词的提取: 1.将文本信息转化为一个无向图,其中每个节点代表一个单词或者短语。 2.在无向图上进行链接建立,若两个节点之间存在相关性,那么就建立一条边。这种相关性可以采用余弦相似度、Jaccard相似度等方法进行计算。 3.初始化每个节点的分数为1.0,在每一轮迭代中,根据节点之间的相似度计算每个节点的分数,然后进行叠加更新,直到收敛为止。 4.根据节点分数的大小,确定文本信息中的关键词。 总之,TextRank算法能够在大规模文本中进行关键词的挖掘,这对于人工处理、文本管理以及自然语言处理等方面都有着重要的实际应用价值。近年来,该算法在搜索引擎、新闻摘要、文本分类、推荐算法等领域的使用越来越广泛,未来也将有着更加广泛的应用前景。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Hello.Reader

请我喝杯咖啡吧😊

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

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

打赏作者

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

抵扣说明:

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

余额充值