Skip to content

Instantly share code, notes, and snippets.

@elpsk
Created March 5, 2020 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elpsk/8b842b3d147c8e1efceba44ca99208f7 to your computer and use it in GitHub Desktop.
Save elpsk/8b842b3d147c8e1efceba44ca99208f7 to your computer and use it in GitHub Desktop.
//
// Twitter SentimentAnalysis
//
import UIKit
import SwifteriOS
import CoreML
class ViewController: UIViewController {
let swifter = Swifter(
consumerKey: "<##KEY##>",
consumerSecret: "<##SECRET##>")
let sentimentClassifier = TweetSentimentClassifier()
override func viewDidLoad() {
super.viewDidLoad()
searchText.delegate = self
}
func sentimentAnalyze( key: String ) {
swifter.searchTweet(
using: key,
lang: "en",
count: 100,
tweetMode: .extended,
success: { results, metadata in
var tweets = [TweetSentimentClassifierInput]()
for i in 0..<100 {
if let tweet = results[i]["full_text"].string {
let tweetForClassification = TweetSentimentClassifierInput(text: tweet)
tweets.append( tweetForClassification )
}
}
do {
var sentimentScore = 0
let predictions = try self.sentimentClassifier.predictions(inputs: tweets)
for prediction in predictions {
let sentiment = prediction.label
if sentiment == "Pos" {
sentimentScore += 1
} else if sentiment == "Neg" {
sentimentScore -= 1
}
}
print( sentimentScore )
} catch {}
}) { _ in }
}
}
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if let text = textField.text { sentimentAnalyze(key: text ) }
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment