NEW: Join my free 100 Days of SwiftUI challenge today! >>

How to perform sentiment analysis on a string using NLTagger

Swift version: 5.1

Paul Hudson    @twostraws   

Sentiment analysis uses machine learning to tell us whether a piece of text is considered positive or negative, and it’s baked right in to iOS with the NaturalLanguage framework.

To perform sentiment analysis takes a handful of lines of code: we create an NLTagger that creates a sentiment score, assign some text for the tagger to analyze, read the sentiment value, then convert it to a Double so it can be used.

Let’s look at the code first, then I’ll break down what it means:

// set up our input
let input = "Hacking with Swift is awesome"

// feed it into the NaturalLanguage framework
let tagger = NLTagger(tagSchemes: [.sentimentScore])
tagger.string = input

// ask for the results
let (sentiment, _) = tagger.tag(at: input.startIndex, unit: .paragraph, scheme: .sentimentScore)

// read the sentiment back and print it
let score = Double(sentiment?.rawValue ?? "0") ?? 0
print(score)

Now let’s break that down, starting with the tagger.tag() call that has three options and two return values.

The options are:

  1. Where to start scanning; in the code above we go from the start of our string.
  2. How much to scan; in the code above we scan the entire paragraph.
  3. Which specific tag scheme we want to read; we only have one, which is the sentiment score.

What we get back is the sentiment score as an NLTag, plus the range where it was found. We don’t care about the range, so we’ll ignore it.

The other value, that sentiment constant, is an NLTag? with a raw value of a String. If everything went to plan that string will contain a Double in the range of -1 (very negative) to +1 (very positive), so to read that value we need to do some careful typecasting:

let score = Double(sentiment?.rawValue ?? "0") ?? 0
print(score)

That means “attempt to read the sentiment’s raw value, but use the string ‘0’ if that fails, then attempt to convert that to a Double, but use the value 0 if that fails.”

The end result will be a score value that is somewhere between -1.0 (very negative) and 1.0 (very positive), or 0.0 if the text is neutral or nothing could be read.

Note: In this example I’ve used a short piece of text, but obviously the framework works best with lots of text – it’s hard to come to a conclusion given only a few words, and you’ll often get inaccurate readings doing so.

LEARN SWIFTUI FOR FREE I have a massive, free SwiftUI video collection on YouTube teaching you how to build complete apps with SwiftUI – check it out!

Available from iOS 13.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5