Classify nouns, verbs, adjectives, and other parts of speech in a string.
Framework
- Natural Language
Overview
Identifying the parts of speech for words in natural language text can help your program understand the meaning of sentences. For example, provided the transcription of a request spoken by the user, you might programmatically determine general intent by looking at only the nouns and verbs.
The example below shows how to use NLTagger to enumerate over natural language text and identify the part of speech for each word.
let text = "The ripe taste of cheese improves with age."
let tagger = NLTagger(tagSchemes: [.lexicalClass])
tagger.string = text
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 {
print("\(text[tokenRange]): \(tag.rawValue)")
}
return true
}
Create an instance of
NLTagger
, specifyinglexical
as the tag scheme to be used.Class Set the string property of the linguistic tagger to the natural language text.
Create the options to omit punctuation and whitespace.
Enumerate over the entire range of the string, specifying
word
as the tag unit andlexical
as the tag scheme, and the tagger options.Class In the enumeration block, take a substring of the original text at
token
to obtain each word.Range Run this code to print out each word and its part of speech on a new line.