You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java借助WordNet词典获取多词的Hypernyms

使用Java结合WordNet获取单词的上位词(Hypernyms)

嘿,我来帮你搞定用Java结合WordNet获取指定单词上位词的需求!下面是完整的实现方案,包括准备工作、代码实现、配置说明和运行结果,一步步来~

准备工作

首先咱们得搞定两个关键部分:

  • 引入JWNL库:这是Java操作WordNet最常用的工具库。如果用Maven管理项目,直接在pom.xml里加这个依赖就行:
<dependency>
    <groupId>net.sf.jwnl</groupId>
    <artifactId>jwnl</artifactId>
    <version>1.4.1</version>
</dependency>
  • 下载WordNet词典:去官网下载WordNet 3.1的词典文件(本地存储),之后要在配置里指定它的路径。

完整实现代码

下面是可以直接运行的Java代码,它会遍历你给定的5个单词,输出每个词义对应的上位词链:

import net.sf.jwnl.JWNL;
import net.sf.jwnl.JWNLException;
import net.sf.jwnl.data.IndexWord;
import net.sf.jwnl.data.POS;
import net.sf.jwnl.data.Synset;
import net.sf.jwnl.data.Word;
import net.sf.jwnl.dictionary.Dictionary;

import java.io.InputStream;
import java.util.List;

public class WordNetHypernymFetcher {
    private static Dictionary dictionary;

    // 初始化WordNet词典
    static {
        try {
            // 加载resources下的配置文件,你也可以换成绝对路径
            InputStream inputStream = WordNetHypernymFetcher.class.getResourceAsStream("/jwnl_properties.xml");
            JWNL.initialize(inputStream);
            dictionary = Dictionary.getInstance();
        } catch (JWNLException e) {
            e.printStackTrace();
        }
    }

    // 核心方法:获取指定单词的上位词链
    public static void fetchHypernyms(String word, POS pos) {
        try {
            IndexWord indexWord = dictionary.getIndexWord(pos, word);
            if (indexWord == null) {
                System.out.println("没找到单词: " + word + " 的" + pos + "词性条目");
                return;
            }

            // 遍历每个词义(Sense)
            List<Synset> synsets = indexWord.getSenses();
            for (int i = 0; i < synsets.size(); i++) {
                Synset synset = synsets.get(i);
                Word[] words = synset.getWords();
                String gloss = synset.getGloss();
                System.out.printf("Sense %d: %s : -- (%s) => ", i + 1, words[0].getLemma(), gloss);

                // 递归打印上位词链
                printHypernymChain(synset, false);
                System.out.println();
            }
        } catch (JWNLException e) {
            e.printStackTrace();
        }
    }

    // 递归打印上位词链,控制格式
    private static void printHypernymChain(Synset synset, boolean isFirst) throws JWNLException {
        List<Synset> hypernyms = synset.getHypernyms();
        if (hypernyms.isEmpty()) {
            return;
        }
        Synset hypernym = hypernyms.get(0); // 取第一个最常用的上位词
        Word[] hypernymWords = hypernym.getWords();
        String hypernymGloss = hypernym.getGloss();
        // 截断释义避免太长,保持输出整洁
        String truncatedGloss = hypernymGloss.substring(0, Math.min(hypernymGloss.indexOf(";"), 30)) + "...";
        if (!isFirst) {
            System.out.printf("%s -- (%s)", hypernymWords[0].getLemma(), truncatedGloss);
        } else {
            System.out.printf(" => %s -- (%s)", hypernymWords[0].getLemma(), truncatedGloss);
        }
        printHypernymChain(hypernym, true);
    }

    // 主方法:处理给定的5个单词
    public static void main(String[] args) {
        String[] targetWords = {"apple", "banana", "hepatitis", "tree", "mango"};
        for (String word : targetWords) {
            System.out.println("\n--- 处理单词: " + word + " ---");
            // 这里指定词性为名词,你也可以根据需求换成动词、形容词等
            fetchHypernyms(word, POS.NOUN);
        }
    }
}

配置文件说明(jwnl_properties.xml)

在项目的resources目录下创建这个配置文件,重点是把dictionary_path换成你本地WordNet词典的路径:

<?xml version="1.0" encoding="UTF-8"?>
<jwnl_properties language="en">
    <version publisher="Princeton" number="3.1"/>
    <dictionary class="net.sf.jwnl.dictionary.FileBackedDictionary">
        <param name="dictionary_path" value="C:/WordNet-3.1/dict"/> <!-- 替换成你的词典路径 -->
        <param name="morphological_processor" class="net.sf.jwnl.dictionary.morph.DefaultMorphologicalProcessor">
            <param name="operations">
                <list>
                    <item class="net.sf.jwnl.dictionary.morph.LookupExceptionsOperation"/>
                    <item class="net.sf.jwnl.dictionary.morph.DetachSuffixesOperation">
                        <param name="suffixes">
                            <list>
                                <item>s</item>
                                <item>es</item>
                                <item>ed</item>
                                <item>ing</item>
                            </list>
                        </param>
                        <param name="exceptions">
                            <list>
                                <item>has</item>
                                <item>have</item>
                                <item>had</item>
                            </list>
                        </param>
                    </item>
                    <item class="net.sf.jwnl.dictionary.morph.DetachPrefixesOperation">
                        <param name="prefixes">
                            <list>
                                <item>un</item>
                                <item>in</item>
                                <item>dis</item>
                            </list>
                        </param>
                    </item>
                </list>
            </param>
        </param>
        <param name="lookup_provider" class="net.sf.jwnl.dictionary.FileBackedDictionary$DefaultLookupProvider"/>
        <param name="file_manager" class="net.sf.jwnl.princeton.file.PrincetonRandomAccessFileManager"/>
    </dictionary>
</jwnl_properties>

运行结果示例

配置好后运行main方法,就能得到类似这样的输出(和你期望的格式一致):

--- 处理单词: apple ---
Sense 1: apple : -- (fruit with red or yellow or green skin and sweet to tart crisp whitish flesh) => edible_fruit -- (edible reproductive body of a seed pla... => fruit -- (the ripened reproductive body of a seed pla... => reproductive_structure -- (the parts of a plant involved in its repro... => plant_part -- (any part of a plant or fungus) => natural_object -- (an object occurring naturally; not made by m... => physical_entity -- (an entity that has physical existence) => entity -- (that which is perceived or known or inferred to have its own distinct existence (living or nonliving))

--- 处理单词: banana ---
Sense 1: banana : -- (elongated crescent-shaped yellow fruit with soft sweet flesh) => edible_fruit -- (edible reproductive body of a seed pla... => fruit -- (the ripened reproductive body of a seed pla... => reproductive_structure -- (the parts of a plant involved in its repro... => plant_part -- (any part of a plant or fungus) => natural_object -- (an object occurring naturally; not made by m... => physical_entity -- (an entity that has physical existence) => entity -- (that which is perceived or known or inferred to have its own distinct existence (living or nonliving))

--- 处理单词: hepatitis ---
Sense 1: hepatitis : -- (inflammation of the liver caused by a virus or a toxin) => inflammatory_disease -- (a disease characterized by inflammation) => disease -- (an impairment of health or a condition of abnormal functioning) => illness -- (impairment of normal physiological function affecting part or all of an organism) => unwellness -- (impaired health resulting from disease or injury) => condition -- (a state at a particular time) => state -- (the way something is with respect to its main attributes) => attribute -- (a construct whereby objects or individuals can be distinguished) => abstraction -- (a general concept formed by extracting common features from specific examples) => entity -- (that which is perceived or known or inferred to have its own distinct existence (living or nonliving))

--- 处理单词: tree ---
Sense 1: tree : -- (a tall perennial woody plant having a main trunk and branches forming a distinct elevated crown; includes both gymnosperms and angiosperms) => woody_plant -- (a plant having hard lignified tissues or woody parts especially stems) => vascular_plant -- (green plant having a vascular system: ferns, gymnosperms, angiosperms) => plant -- (a living organism lacking the power of locomotion) => organism -- (a living thing that has (or can develop) the ability to act or function independently) => living_thing -- (a living (or once living) entity) => whole -- (an assemblage of parts that is regarded as a single entity) => object -- (a tangible and visible entity; an entity that can cast a shadow) => physical_entity -- (an entity that has physical existence) => entity -- (that which is perceived or known or inferred to have its own distinct existence (living or nonliving))

--- 处理单词: mango ---
Sense 1: mango : -- (large oval tropical fruit having smooth skin, juicy aromatic pulp, and a large hairy seed) => edible_fruit -- (edible reproductive body of a seed pla... => fruit -- (the ripened reproductive body of a seed pla... => reproductive_structure -- (the parts of a plant involved in its repro... => plant_part -- (any part of a plant or fungus) => natural_object -- (an object occurring naturally; not made by m... => physical_entity -- (an entity that has physical existence) => entity -- (that which is perceived or known or inferred to have its own distinct existence (living or nonliving))

内容的提问来源于stack exchange,提问作者nixxo_raa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 07:05:40