Android Studio中使用Stanford Core NLP加载模型报错求助
问题解决:Stanford Core NLP加载模型失败(Error while loading a tagger)
问题根源
你当前代码里的pos.model和parse.model配置的是jar文件路径,但Stanford Core NLP要求这两个参数指向jar包内部的具体模型文件路径,而非jar文件本身。同时Android环境下不能直接用libs/这类相对路径访问jar内资源,得用类路径下的模型文件路径。
解决方案
- 修正模型路径配置
西班牙语对应的模型文件在stanford-corenlp-4.5.4-models-spanish.jar内部的正确路径:
- POS标注模型:
edu/stanford/nlp/models/pos-tagger/spanish/spanish-distsim.tagger - 句法解析模型:
edu/stanford/nlp/models/lexparser/spanishPCFG.ser.gz
- 确保jar包依赖正确引入
在模块级build.gradle文件中添加对libs目录下jar包的依赖:
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) // 其他项目依赖... }
- 修改代码中的Properties配置
替换原有的模型路径配置,修改后的完整代码:
fun analyzeAndDisplayTree(sentence: String): String { try { val props = Properties() props.setProperty("annotators", "tokenize, ssplit, pos, parse") props.setProperty("tokenize.language", "es") // 修正POS模型路径 props.setProperty("pos.model", "edu/stanford/nlp/models/pos-tagger/spanish/spanish-distsim.tagger") // 修正解析模型路径 props.setProperty("parse.model", "edu/stanford/nlp/models/lexparser/spanishPCFG.ser.gz") val pipeline = StanfordCoreNLP(props) val document = pipeline.process(sentence) val parsedSentence = document.get(CoreAnnotations.SentencesAnnotation::class.java)[0] val tree: Tree = parsedSentence.get(TreeCoreAnnotations.TreeAnnotation::class.java) return "Sentence: $parsedSentence\nParse Tree: ${tree.pennString()}" } catch (e: Exception) { return "Error: ${e.message}\n${e.stackTraceToString()}" // 建议添加堆栈信息,方便后续排查问题 } }
额外注意事项
- Stanford Core NLP的jar包体积较大,在Android设备上运行可能存在性能和内存占用过高的问题,测试时需关注设备运行状态。
- 若仍出现加载失败,可尝试将模型文件从jar中提取出来,放在项目
assets目录下,再通过assets路径访问(需额外处理资源读取逻辑)。
内容的提问来源于stack exchange,提问作者Eduardo
相关产品推荐
相关产品推荐

