Skip to content

Instantly share code, notes, and snippets.

@jepers
Created June 2, 2017 22:57
Show Gist options
  • Save jepers/f8857ea1387e8ee1cddcef36d0c2e315 to your computer and use it in GitHub Desktop.
Save jepers/f8857ea1387e8ee1cddcef36d0c2e315 to your computer and use it in GitHub Desktop.
A simple way to generate random sentences using NSSpellChecker.
import AppKit
let filteredWords = Set<String>(["app", "apps"])
let questionPrefixes = Set<String>([
"Which", "What", "Who", "Whom", "Whose", "Where", "When", "How", "Why", "Can",
"May", "Will", "Is", "Do", "Shall", "Has", "Must", "Would", "Could", "Should"
])
extension String {
func addingRandomCompletion(maximumIndex: Int? = 4) -> String {
let completions = NSSpellChecker.shared().completions(
forPartialWordRange: NSRange(location: (self as NSString).length, length: 0),
in: self, language: "en", inSpellDocumentWithTag: 0)!
.filter { filteredWords.contains($0) == false }
var upperIndexBound = completions.count
if let mi = maximumIndex { upperIndexBound = min(mi+1, completions.count) }
return self + completions[Int(arc4random_uniform(UInt32(upperIndexBound)))]
}
func lexicalClassTags() -> [String] {
return linguisticTags(in: startIndex ..< endIndex, scheme: "LexicalClass",
options: [.joinNames, .omitWhitespace])
}
}
func randomSentence() -> String {
var s = ""
while true {
s = s.addingRandomCompletion(maximumIndex: s.isEmpty ? nil : 3)
let ltags = s.lexicalClassTags()
if ltags.count > 3 && ltags.last == "Noun" && ltags.contains("Verb") && arc4random() & 7 > 0 {
return s + (questionPrefixes.contains(where: { s.hasPrefix($0) }) ? "?" : ".")
} else {
s += " "
}
}
}
for _ in 0 ..< 10 {
print(randomSentence() + "\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment