NSLinguisticTagger: отфильтровать указанный токен в зависимости от типа тега - PullRequest
0 голосов
/ 14 ноября 2018

Я пытаюсь отфильтровать определенные токены по их тегам.Когда я запускаю свой код, я получаю это как вывод.Я хочу получить только прилагательные и вывести их.Есть ли простой способ сделать это?

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 Ответ

0 голосов
/ 14 ноября 2018

Вы можете просто проверить, имеет ли 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])

Что печатает:

Необязательно (["yellow", "little", "grey"])
Необязательно (["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)

Что выводит:

Кот охотится за мышью вокруг блока

...