您可以简单地检查 atag
是否是闭包中的类型.adjective
,enumerateTags
并且只有在它是时才继续:
let sentence = "The yellow cat hunts the little gray mouse around the block"
let options: NSLinguisticTagger.Options = [.omitWhitespace, .omitPunctuation, .joinNames]
let schemes = NSLinguisticTagger.availableTagSchemes(forLanguage: "en")
let tagger = NSLinguisticTagger(tagSchemes: schemes, options: Int(options.rawValue))
tagger.string = sentence
tagger.enumerateTags(in: NSRange(location: 0, length: sentence.count), scheme: .nameTypeOrLexicalClass, options: options) { (tag, tokenRange, _, _) in
guard tag == .adjective, let adjectiveRange = Range(tokenRange, in: sentence) else { return }
let adjectiveToken = sentence[adjectiveRange]
print(adjectiveToken)
}
这打印出来:
黄色
小
灰色
编辑
如果您想要多个标记类型的标记,您可以将标记存储在字典中,并将标记作为键:
let sentence = "The yellow cat hunts the little gray mouse around the block"
let options: NSLinguisticTagger.Options = [.omitWhitespace, .omitPunctuation, .joinNames]
let schemes = NSLinguisticTagger.availableTagSchemes(forLanguage: "en")
let tagger = NSLinguisticTagger(tagSchemes: schemes, options: Int(options.rawValue))
tagger.string = sentence
var tokens: [NSLinguisticTag: [String]] = [:]
tagger.enumerateTags(in: NSRange(location: 0, length: sentence.count), scheme: .nameTypeOrLexicalClass, options: options) { (tag, tokenRange, _, _) in
guard let tag = tag, let range = Range(tokenRange, in: sentence) else { return }
let token = String(sentence[range])
if tokens[tag] != nil {
tokens[tag]!.append(token)
} else {
tokens[tag] = [token]
}
}
print(tokens[.adjective])
print(tokens[.noun])
打印出来:
可选([“黄色”,“小”,“灰色”])
可选([“猫”,“鼠标”,“块”])
编辑#2
如果您希望能够从文本中删除某些标签,您可以编写如下扩展:
extension NSLinguisticTagger {
func eliminate(unwantedTags: [NSLinguisticTag], from text: String, options: NSLinguisticTagger.Options) -> String {
string = text
var textWithoutUnwantedTags = ""
enumerateTags(in: NSRange(location: 0, length: text.utf16.count), scheme: .nameTypeOrLexicalClass, options: options) { (tag, tokenRange, _, _) in
guard
let tag = tag,
!unwantedTags.contains(tag),
let range = Range(tokenRange, in: text)
else { return }
let token = String(text[range])
textWithoutUnwantedTags += " \(token)"
}
return textWithoutUnwantedTags.trimmingCharacters(in: .whitespaces)
}
}
然后你可以像这样使用它:
let sentence = "The yellow cat hunts the little gray mouse around the block"
let options: NSLinguisticTagger.Options = [.omitWhitespace, .omitPunctuation, .joinNames]
let schemes = NSLinguisticTagger.availableTagSchemes(forLanguage: "en")
let tagger = NSLinguisticTagger(tagSchemes: schemes, options: Int(options.rawValue))
let sentenceWithoutAdjectives = tagger.eliminate(unwantedTags: [.adjective], from: sentence, options: options)
print(sentenceWithoutAdjectives)
打印出来:
猫在街区周围猎杀老鼠