Skip to content

Instantly share code, notes, and snippets.

@EricR
Last active December 31, 2015 12:59
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 EricR/7990041 to your computer and use it in GitHub Desktop.
Save EricR/7990041 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"strings"
)
func nGram(text string, n int) (grams []string) {
words := strings.Split(text, " ")
limit := len(words) - (n - 1)
for i := 0; i < limit; i++ {
grams = append(grams, strings.Join(words[i:(i+n)], " "))
}
return
}
func main() {
grams := nGram("The fox jumps over the lazy dog", 3)
fmt.Printf("%q", grams) // => ["The fox jumps" "fox jumps over" "jumps over the" "over the lazy" "the lazy dog"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment