SALE ENDS TODAY: Save 50% on all Swift books and bundles! >>

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.

SPONSORED Instabug helps you identify and resolve severe crashes quickly. You can retrace in-app events and know exactly which line of code caused the crash along with environment details, network logs, repro steps, and the session profiler. Ask more questions or keep users up-to-date with in-app replies straight from your dashboard. Instabug takes data privacy seriously, so no one sees your data but you! See more detailed features comparison and try Instabug's crash reporting SDK for free.

Save 50% on all books and bundles

The biggest ever Hacking with Swift sale is now on, letting you save 50% on all books and bundles. Learn something new with Swift and enjoy great savings while the sale lasts!

Click here to save 50% in our Black Friday sale!

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.

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5