BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

How to perform sentiment analysis on a string using NLTagger

Swift version: 5.10

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.

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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 Pro SwiftUI 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 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 Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.