简体   繁体   中英

NSLinguisticTagger: Filter out Specified Token Depending on Tag Type

I am trying to filter out specific tokens based on their tags. When I run my code I get this as the output. I want to only retrieve the adjectives and have that outputted. Is there an easy way to do this?

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: "Hello World this is my main goal, to take these words and figure out the adjectives, verbs and nouns")

You can simply check if a tag is of type .adjective in the enumerateTags closure and only continue if it is:

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)
}

This prints out:

yellow
little
gray

EDIT

If you want the tokens of more than one tag type you could store the tokens in a dictionary with the tags as keys:

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])

Which prints out:

Optional(["yellow", "little", "gray"])
Optional(["cat", "mouse", "block"])

EDIT#2

If you want to be able to remove certain tags from a text you could write an extension like this:

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)
    }
}

Then you can use it like this:

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)

Which prints out:

The cat hunts the mouse around the block

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM