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

求助:NLTagger.enumerateTags方法在模拟器中始终返回"otherWord"

NLTagger.enumerateTags返回"otherWord"的模拟器解决方案

在模拟器中使用NLTagger.enumerateTags时所有单词都返回"otherWord",核心原因是未显式指定文本语言,导致框架无法正确加载对应的词性标注模型。

修复步骤:

在创建NLTagger实例并设置string后,添加一行代码显式指定文本语言为英文:

tagger.setLanguage(.english, range: text.startIndex..<text.endIndex)

修改后的完整代码:

//  ContentView.swift

import SwiftUI
import NaturalLanguage

struct ContentView: View {
    var body: some View {
        VStack {
            Text(example())
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

func example() -> String{
    let text = "The ripe taste of cheese improves with age."
    var res = ""
    let tagger = NLTagger(tagSchemes: [.lexicalClass])
    tagger.string = text
    // 新增:显式指定文本语言
    tagger.setLanguage(.english, range: text.startIndex..<text.endIndex)
    let options: NLTagger.Options = [.omitPunctuation, .omitWhitespace]
    tagger.enumerateTags(in: text.startIndex..<text.endIndex, unit: .word, scheme: .lexicalClass, options: options) { tag, tokenRange in
        if let tag = tag {
            res += "\(text[tokenRange]): \(tag.rawValue)\n"
        }
        return true
    }
    return res
}

说明:

模拟器环境下,NLTagger的自动语言检测可能因模型缺失或系统语言配置问题失效,显式指定语言后框架能精准加载对应词性分析模型,即可正常返回正确的词性标签(如determiner、adjective、noun等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 22:32:43