NLGElement调用addComplement方法报错问题咨询及替代方案求助
嘿,这个问题我刚好碰到过!让我给你解释清楚为啥报错,以及怎么解决~
为什么会报错?
NLGElement是SimpleNLG里的顶层通用接口,它只定义了所有语法单元都有的基础方法(比如设置特征、获取文本等),但addComplement()方法并不是它的标准方法——这个方法是属于更具体的子类(比如Clause从句、PhraseElement短语)的。
你用factory.createSentence("my dog is happy")返回的是Sentence类型的对象,而Sentence类并没有实现addComplement()方法,所以编译器会提示你“The method addComplement() is undefined for the type NLGElement”。
替代方案:针对具体语法单元添加补语
补语是依附于句子内部的某个成分(比如谓语从句、名词短语)的,所以你需要先构建这些具体的语法单元,添加补语后再组装成句子。这里有两种常见场景的实现:
场景1:给谓语部分添加补语(比如你要实现"My dog is happy with me")
先构建核心从句,给从句添加补语,再把从句转为句子:
Lexicon lexicon = new XMLLexicon(); NLGFactory factory = new NLGFactory(lexicon); // 1. 先构建核心从句(主语+谓语+表语) Clause coreClause = factory.createClause("my dog", "be", "happy"); // 2. 给从句添加补语 coreClause.addComplement("with me"); // 3. 将从句包装成完整句子 Sentence s1 = factory.createSentence(coreClause); // 生成最终文本 Realiser realiser = new Realiser(lexicon); System.out.println(realiser.realise(s1).getRealisation()); // 输出:My dog is happy with me.
场景2:给名词短语添加补语(比如"My dog that plays with me is happy")
如果补语是用来修饰名词的,先定位到目标名词短语,添加补语后再组装句子:
Lexicon lexicon = new XMLLexicon(); NLGFactory factory = new NLGFactory(lexicon); // 1. 构建名词短语 NLGElement dogPhrase = factory.createNounPhrase("my", "dog"); // 2. 给名词短语添加补语(这里是定语从句形式的补语) dogPhrase.addComplement("that plays with me"); // 3. 用修饰后的名词短语构建从句,再转为句子 Clause coreClause = factory.createClause(dogPhrase, "be", "happy"); Sentence s1 = factory.createSentence(coreClause); // 生成最终文本 Realiser realiser = new Realiser(lexicon); System.out.println(realiser.realise(s1).getRealisation()); // 输出:My dog that plays with me is happy.
额外说明
SimpleNLG的设计逻辑是分层构建语法单元:从最基础的单词、短语,到从句,最后组装成句子。直接操作Sentence这种顶层单元无法进行细粒度的语法修改,必须深入到内部的具体成分(从句、短语)才能调用addComplement()这类针对性方法。
内容的提问来源于stack exchange,提问作者mee
相关产品推荐
相关产品推荐

