Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marlonjames71/afca4d2aec9012a3d1a0f21071e573ea to your computer and use it in GitHub Desktop.
Save marlonjames71/afca4d2aec9012a3d1a0f21071e573ea to your computer and use it in GitHub Desktop.
Orginally this was used for a project I worked on where the user was creating a sort of journal entry that had a title. You'd pass the title into this parser and when the user wanted to add a cover photo to the entry using Unsplash, the parser would parse the entry title so when Unsplash appears, it already showed relevant results to the entry.
// This was originally done in Playgrounds
// You can plop this in Playgrounds and it should work.
import UIKit
let title = "The best camping trip of the year with the best friends"
func checkForValidQueryString(_ string: String) -> Bool {
guard
!string.isEmpty,
// When the user was creating an entry, they could create what was called a Moment or a Story.
// We want to make sure the user has added an actual title before parsing, not using the placeholders.
string != "Moment Name",
string != "Story Name"
else { return false }
return true
}
func parseImportantWords(from string: String) -> String {
var result = ""
let options = NSLinguisticTagger.Options.omitWhitespace.rawValue | NSLinguisticTagger.Options.joinNames.rawValue
let tagger = NSLinguisticTagger(tagSchemes: NSLinguisticTagger.availableTagSchemes(forLanguage: "en"), options: Int(options))
tagger.string = string
let range = NSRange(location: 0, length: string.utf16.count)
tagger.enumerateTags(in: range,
scheme: .nameTypeOrLexicalClass,
options: NSLinguisticTagger.Options(rawValue: options)) { tag, tokenRange, sentenceRange, stop in
guard let range = Range(tokenRange, in: string) else { return }
let token = string[range]
if let tag = tag {
if tag.rawValue == "Noun" || tag.rawValue == "Verb" {
guard !result.contains(token) else { return }
result += "\(token) "
}
}
}
return result
}
/// Validates string from Moment or Story Title and produces a relevant starting query.
func produceQueryString(from input: String) -> String {
let startingQuery: String
if checkForValidQueryString(input) {
startingQuery = parseImportantWords(from: input)
} else {
// If there is no valid string to parse, then I just gave it word that is general, but relevant to the app.
startingQuery = "life"
}
return startingQuery
}
let startingQuery = produceQueryString(from: title)
print("Query: \(startingQuery)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment