N-grams: Difference between revisions

1,039 bytes added ,  1 year ago
Created Nim solution.
(Added C)
(Created Nim solution.)
Line 313:
("Li", 1) ("iv", 2) ("ve", 2) ("e ", 1) (" a", 1) ("an", 1) ("nd", 1) ("d ", 1)
(" l", 2) ("le", 1) ("et", 1) ("t ", 1) ("li", 1)
</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="Nim">import std/[strutils, tables]
 
type NGrams = CountTable[string]
 
func ngrams(text: string; n: Positive): NGrams =
for i in 0..(text.len - n):
result.inc(text[i..<(i + n)].toLowerAscii)
 
const Text = "Live and let live"
 
for n in 2..4:
echo n, "-grams:"
var ng = Text.ngrams(n)
ng.sort() # To display n-grams with higher score first.
for key, count in ng:
echo "“$1”: $2".format(key, count)
echo()
</syntaxhighlight>
 
<pre>2-grams:
“ve”: 2
“li”: 2
“iv”: 2
“ l”: 2
“d ”: 1
“et”: 1
“t ”: 1
“an”: 1
“nd”: 1
“e ”: 1
“le”: 1
“ a”: 1
 
3-grams:
“ive”: 2
“liv”: 2
“ le”: 1
“nd ”: 1
“and”: 1
“et ”: 1
“ve ”: 1
“t l”: 1
“ an”: 1
“d l”: 1
“e a”: 1
“let”: 1
“ li”: 1
 
4-grams:
“live”: 2
“ liv”: 1
“ and”: 1
“e an”: 1
“ let”: 1
“and ”: 1
“d le”: 1
“t li”: 1
“nd l”: 1
“et l”: 1
“ive ”: 1
“let ”: 1
“ve a”: 1
</pre>
 
256

edits