Отфильтровать указанный токен в зависимости от типа тега
Я пытаюсь отфильтровать определенные токены на основе их тегов. Когда я запускаю свой код, я получаю это как вывод. Я хочу только получить прилагательные и вывести их. Есть простой способ сделать это?
Hello: NSLinguisticTag(_rawValue: Interjection)
World: NSLinguisticTag(_rawValue: Noun)
this: NSLinguisticTag(_rawValue: Determiner)
is: NSLinguisticTag(_rawValue: Verb)
my: NSLinguisticTag(_rawValue: Determiner)
main: NSLinguisticTag(_rawValue: Adjective)
goal: NSLinguisticTag(_rawValue: Noun)
tokenizeText (inputtedText: "Привет, мир, это моя главная цель, взять эти слова и выяснить прилагательные, глаголы и существительные")
1 ответ
Вы можете просто проверить, если tag
имеет тип .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])
Который распечатывает:
Необязательно (["желтый", "маленький", "серый"])
Необязательно (["cat", "mouse", "block"])
EDIT # 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)
Который распечатывает:
Кот охотится за мышью вокруг блока