如何用Python3的SimpleNLG生成正确的WHAT_OBJECT类型疑问语句?
如何用Python版SimpleNLG生成正确的“What are the colors of lightsabers?”问句
我需要生成问句 "What are the colors of lightsabers?",使用Java版SimpleNLG的Python移植版本(Python 3.11),但当前代码生成了错误语句 "What are lightsaber the colors of?",错误代码如下:
sentence = nlgFactory.createClause() sentence.setSubject("lightsaber") sentence.setPlural("true") sentence.setVerb("be") sentence.addFrontModifier("the colors of") sentence.setFeature(Feature.INTERROGATIVE_TYPE, InterrogativeType.WHAT_OBJECT) return realiser.realiseSentence(sentence)
解决方案
问题出在错误使用addFrontModifier处理所属关系,且疑问类型设置不当。正确做法是先构建完整的名词短语作为主语,再匹配对应的疑问类型。
简洁实现代码
# 构建完整的主语名词短语:the colors of lightsabers subject_phrase = nlgFactory.createNounPhrase("the", "color") subject_phrase.setPlural(True) # 添加所属补语,指定介词of subject_phrase.addComplement(nlgFactory.createNounPhrase("lightsaber", is_plural=True), "of") # 创建分句并设置属性 sentence = nlgFactory.createClause(subject_phrase, "be") sentence.setFeature(Feature.INTERROGATIVE_TYPE, InterrogativeType.WHAT_SUBJECT) return realiser.realiseSentence(sentence)
关键说明
- 用
createNounPhrase结合addComplement构建带所属关系的短语,避免前置修饰导致的语序混乱 - 疑问类型设为
WHAT_SUBJECT,因为问句中"What"是对主语"the colors of lightsabers"的提问 - 明确设置名词复数,确保语法正确性
内容的提问来源于stack exchange,提问作者edoardo
相关产品推荐
相关产品推荐

