Letter frequency: Difference between revisions

Add Refal
No edit summary
(Add Refal)
 
(24 intermediate revisions by 16 users not shown)
Line 15:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F countletters(s)
DefaultDict[Char, Int] results
L(char) s
Line 25:
:start:
L(letter, count) countletters(File(:argv[1]).read())
print(letter‘=’count)</langsyntaxhighlight>
 
{{out}}
Line 43:
contained in the file.
 
<langsyntaxhighlight lang="8080asm">bdos: equ 5 ; CP/M syscalls
putch: equ 2 ; Print a character
puts: equ 9 ; Print a string
Line 159:
numend: db 13,10,'$' ; a 16-bit number, plus newline.
 
</syntaxhighlight>
</lang>
 
=={{header|8th}}==
<langsyntaxhighlight lang="8th">
 
needs map/iter
Line 204:
print-results
bye ;
</syntaxhighlight>
</lang>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program cptletters64.s */
 
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE, 300000
 
/************************************/
/* Initialized data */
/************************************/
.data
szMessOpen: .asciz "File open error.\n"
szMessStat: .asciz "File information error.\n"
szMessRead: .asciz "File read error.\n"
szMessClose: .asciz "File close error.\n"
szMessDecryptText: .asciz "Decrypted text :\n"
szMessCryptText: .asciz "Encrypted text :\n"
szMessErrorChar: .asciz "Character text not Ok!\n"
szFileName: .asciz "unixdict.txt"
//szFileName: .asciz "test1.txt"
szMessResult: .asciz "Result: = "
szCarriageReturn: .asciz "\n"
szMessStart: .asciz "Program 64 bits start.\n"
/************************************/
/* UnInitialized data */
/************************************/
.bss
sZoneConv: .skip 24
tabCptLetters: .skip 8 * 52 // (A-Z a-z) counter array
sBuffer: .skip BUFFERSIZE // file buffer
/************************************/
/* code section */
/************************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessStart
bl affichageMess
mov x0,AT_FDCWD
ldr x1,qAdrszFileName // file name
mov x2,#O_RDWR // flags
mov x3,#0 // mode
mov x8,#OPEN // file open
svc 0
cmp x0,#0 // error ?
ble 99f
mov x9,x0 // FD save
 
mov x0,x9
ldr x1,qAdrsBuffer
ldr x2,#iBufferSize
mov x8,#READ // call system read file
svc 0
cmp x0,#0 // error read ?
blt 97f
mov x6,x0 // file size
mov x0,x9
mov x8,#CLOSE // call system close file
svc 0
cmp x0,#0 // error close ?
blt 96f
ldr x0,qAdrsBuffer
mov x1,x6
bl cptLetters
b 100f
96:
ldr x0,qAdrszMessClose
bl affichageMess
mov x0,#-1 // error
b 100f
97:
ldr x0,qAdrszMessRead
bl affichageMess
mov x0,#-1 // error
b 100f
99:
ldr x0,qAdrszMessOpen
bl affichageMess
mov x0,#-1 // error
 
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform the system call
 
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessStart: .quad szMessStart
qAdrszFileName: .quad szFileName
qAdrszMessOpen: .quad szMessOpen
qAdrszMessRead: .quad szMessRead
qAdrszMessStat: .quad szMessStat
qAdrszMessClose: .quad szMessClose
qAdrsBuffer: .quad sBuffer
iBufferSize: .quad BUFFERSIZE
/***************************************************/
/* letters frequency */
/***************************************************/
/* r0 contains a file buffer */
/* r1 contains string length */
cptLetters:
stp x1,lr,[sp,-16]!
stp x2,x3,[sp,-16]!
stp x4,x5,[sp,-16]!
stp x6,x7,[sp,-16]!
ldr x4,qAdrtabCptLetters // counter array
mov x3,#0 // index string
1:
ldrb w2,[x0,x3] // load byte of string
cmp x2,#'A' // select alpha characters lower or upper
blt 5f
cmp x2,#'Z'
bgt 2f
sub x5,x2,#65 // convert ascii upper in index array (0-25)
b 3f
2:
cmp x2,#'z'
bgt 5f
cmp x2,#'a'
blt 5f
sub x5,x2,#97 - 26 // convert ascii lower in index array (26,52]
3:
ldr x7,[x4,x5,lsl #3] // load counter of load character
add x7,x7,#1 // increment counter
str x7,[x4,x5,lsl #3] // and store
5:
add x3,x3,#1 // increment text index
cmp x3,x1 // end ?
blt 1b // and loop
ldr x7,qAdrszMessResult
mov x2,65 // for upper ascci character
mov x3,#0
6: // result display
ldr x1,[x4,x3,lsl #3] // load counter
cmp x1,#0 // if zero not display
beq 7f
cmp x3,#25 // upper ?
add x2,x3,65 // for upper ascci character
add x8,x3,#97 - 26 // lower
csel x6,x2,x8,le // compute ascii character
strb w6,[x7,#9] // store in message
mov x0,x1 // convert count in decimal
ldr x1,qAdrsZoneConv
bl conversion10
ldr x0,qAdrszMessResult // and display
bl affichageMess
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
7:
add x3,x3,#1
cmp x3,#52
blt 6b
100:
ldp x6,x7,[sp],16
ldp x4,x5,[sp],16
ldp x2,x3,[sp],16
ldp x1,lr,[sp],16 // TODO: retaur à completer
ret
qAdrtabCptLetters: .quad tabCptLetters
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"
 
</syntaxhighlight>
{{Out}}
<pre>
Program 64 bits start.
Result: a = 16421
Result: b = 4115
Result: c = 8216
Result: d = 5799
Result: e = 20144
Result: f = 2662
Result: g = 4129
Result: h = 5208
Result: i = 13980
Result: j = 430
Result: k = 1925
Result: l = 10061
Result: m = 5828
Result: n = 12097
Result: o = 12738
Result: p = 5516
Result: q = 378
Result: r = 13436
Result: s = 10210
Result: t = 12836
Result: u = 6489
Result: v = 1902
Result: w = 1968
Result: x = 617
Result: y = 3633
Result: z = 433
</pre>
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun increment-alist (tbl key)
(cond ((endp tbl) (list (cons key 1)))
((eql (car (first tbl)) key)
Line 222 ⟶ 430:
 
(defun letter-freq (str)
(freq-table (coerce str 'list)))</langsyntaxhighlight>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit
 
CARD ARRAY histogram(256)
Line 286 ⟶ 494:
 
LMARGIN=old ;restore left margin on the screen
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Letter_frequency.png Screenshot from Atari 8-bit computer]
Line 309 ⟶ 517:
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Letter_Frequency is
Line 328 ⟶ 536:
end if;
end loop;
end Letter_Frequency;</langsyntaxhighlight>
 
{{out}} (counting the characters of its own source code):
Line 343 ⟶ 551:
 
=={{header|Aikido}}==
<langsyntaxhighlight lang="aikido">import ctype
 
var letters = new int [26]
Line 361 ⟶ 569:
foreach i letters.size() {
println (cast<char>('a' + i) + " " + letters[i])
}</langsyntaxhighlight>
 
=={{header|Aime}}==
Letters proper:
<langsyntaxhighlight lang="aime">file f;
index x;
integer c;
Line 379 ⟶ 587:
o_form("%c: /w5/\n", c, x[c] += x[c + 'a' - 'A'] += 0);
c += 1;
}</langsyntaxhighlight>
All chars:
<langsyntaxhighlight lang="aime">file f;
index x;
integer c, n;
Line 393 ⟶ 601:
for (c, n in x) {
o_form("%c: /w5/\n", c, n);
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">
BEGIN
[0:max abs char]INT histogram;
Line 423 ⟶ 631:
FOR i FROM ABS "a" TO ABS "z" DO printf (($a3xg(0)l$, REPR i, histogram[i])) OD
END
</syntaxhighlight>
</lang>
{{out}} Counting letters in its own source code:
<pre>
Line 450 ⟶ 658:
 
=={{header|APL}}==
<langsyntaxhighlight lang="apl"> freq←{(⍪∪⍵),+/(∪⍵)∘.⍷⍵}
 
freq 0 1 2 3 2 3 4 3 4 4 4
Line 464 ⟶ 672:
l 2
o 2
n 1</langsyntaxhighlight>
 
The above solution doesn't do the "open a text file" part of the task. File I/O is implementation-dependent, but here's how to do it in Dyalog:
 
{{works with|Dyalog APL}}
<langsyntaxhighlight lang="apl"> text ← ⊃⎕nget 'filename'</langsyntaxhighlight>
 
... after which the above <tt>freq</tt> function can be applied to <tt>text</tt>.
Line 477 ⟶ 685:
This is probably best handled with vanilla AppleScript and ASObjC each each doing what it does best. The test text used here is the one specified for the [https://www.rosettacode.org/wiki/Word_frequency Word frequency] task.
 
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use scripting additions
Line 524 ⟶ 732:
-- Test with the text file for the "Word frequency" task.
set theFile to ((path to desktop as text) & "135-0.txt") as alias
return letterFrequencyinFile(theFile)</langsyntaxhighlight>
 
{{output}}
Line 533 ⟶ 741:
If we just want to get something up and running (and tabulating output) with a minimum of new code –
enough to read the frequencies of shortish texts – we can quickly click together a composition of generic functions.
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 1,040 ⟶ 1,248:
set my text item delimiters to dlm
return s
end unwords</langsyntaxhighlight>
{{Out}}
<pre>SPACE -> 1330 p -> 138 " -> 28 k -> 5
Line 1,070 ⟶ 1,278:
we can do something a little faster with a list of simple regular expressions, again composing a solution from existing generic functions.
 
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 1,375 ⟶ 1,583:
end tell
end if
end zipWith</langsyntaxhighlight>
{{Out}}
<pre>e -> 332590
Line 1,403 ⟶ 1,611:
q -> 2533
z -> 1906</pre>
 
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="gwbasic"> 100 LET F$ = "TEXT FILE"
110 LET D$ = CHR$ (4)
120 DIM C(255)
130 PRINT D$"OPEN "F$
140 FOR Q = 0 TO 1 STEP 0
150 PRINT D$"READ "F$
160 ONERR GOTO 240
170 GET C$
180 POKE 216,0
190 LET C = ASC (C$)
200 LET C(C) = C(C) + 1
210 PRINT
220 NEXT
230 STOP
240 POKE 216,0
250 LET E = PEEK (222)
260 PRINT D$"CLOSE "F$
270 IF E < > 5 THEN RESUME
280 FOR I = 0 TO 255
290 IF C(I) THEN GOSUB 320
300 NEXT I
310 END
320 IF I < 32 THEN PRINT "^" CHR$ (64 + I);
330 IF I > = 32 AND I < 128 THEN PRINT CHR$ (I);
340 IF I > 127 THEN PRINT "CHR$("I")";
350 PRINT "="C(I)" ";
360 RETURN</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program cptletters.s */
 
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../constantes.inc"
.equ READ, 3
.equ WRITE, 4
.equ OPEN, 5
.equ CLOSE, 6
.equ O_RDWR, 0x0002 @ open for reading and writing
.equ BUFFERSIZE, 300000
/************************************/
/* Initialized data */
/************************************/
.data
szMessOpen: .asciz "File open error.\n"
szMessStat: .asciz "File information error.\n"
szMessRead: .asciz "File read error.\n"
szMessClose: .asciz "File close error.\n"
szMessDecryptText: .asciz "Decrypted text :\n"
szMessCryptText: .asciz "Encrypted text :\n"
szMessErrorChar: .asciz "Character text not Ok!\n"
szFileName: .asciz "unixdict.txt"
//szFileName: .asciz "test1.txt"
szMessResult: .asciz "Result: = "
szCarriageReturn: .asciz "\n"
szMessStart: .asciz "Program 32 bits start.\n"
/************************************/
/* UnInitialized data */
/************************************/
.bss
sZoneConv: .skip 24
tabCptLetters: .skip 4 * 52 @ (A-Z a-z) counter array
sBuffer: .skip BUFFERSIZE @ file buffer
/************************************/
/* code section */
/************************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessStart
bl affichageMess
ldr r0,iAdrszFileName @ file name
mov r1,#O_RDWR @ flags
mov r2,#0 @ mode
mov r7,#OPEN @ file open
svc 0
cmp r0,#0 @ error ?
ble 99f
mov r8,r0 @ FD save
 
mov r0,r8
ldr r1,iAdrsBuffer
ldr r2,#iBufferSize
mov r7,#READ @ call system read file
svc 0
cmp r0,#0 @ error read ?
blt 97f
mov r6,r0 @ file size
mov r0,r8
mov r7,#CLOSE @ call system close file
svc 0
cmp r0,#0 @ error close ?
blt 96f
ldr r0,iAdrsBuffer
mov r1,r6
bl cptLetters
b 100f
96:
ldr r0,iAdrszMessClose
bl affichageMess
mov r0,#-1 @ error
b 100f
97:
ldr r0,iAdrszMessRead
bl affichageMess
mov r0,#-1 @ error
b 100f
99:
ldr r0,iAdrszMessOpen
bl affichageMess
mov r0,#-1 @ error
 
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform the system call
 
iAdrsZoneConv: .int sZoneConv
iAdrszMessResult: .int szMessResult
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessStart: .int szMessStart
iAdrszFileName: .int szFileName
iAdrszMessOpen: .int szMessOpen
iAdrszMessRead: .int szMessRead
iAdrszMessStat: .int szMessStat
iAdrszMessClose: .int szMessClose
iAdrsBuffer: .int sBuffer
iBufferSize: .int BUFFERSIZE
/***************************************************/
/* letters frequency */
/***************************************************/
/* r0 contains a file buffer */
/* r1 contains string length */
cptLetters:
push {r1-r7,lr} @ save registers
ldr r4,iAdrtabCptLetters @ counter array
mov r3,#0 @ index string
1:
ldrb r2,[r0,r3] @ load byte of string
cmp r2,#'A' @ select alpha characters lower or upper
blt 5f
cmp r2,#'Z'
bgt 2f
sub r5,r2,#65 @ convert ascii upper in index array (0-25)
b 3f
2:
cmp r2,#'z'
bgt 5f
cmp r2,#'a'
blt 5f
sub r5,r2,#97 - 26 @ convert ascii lower in index array (26,52]
3:
ldr r7,[r4,r5,lsl #2] @ load counter of load character
add r7,r7,#1 @ increment counter
str r7,[r4,r5,lsl #2] @ and store
5:
add r3,r3,#1 @ increment text index
cmp r3,r1 @ end ?
blt 1b @ and loop
ldr r7,iAdrszMessResult
mov r3,#0
6: @ result display
ldr r1,[r4,r3,lsl #2] @ load counter
cmp r1,#0 @ if zero not display
beq 7f
cmp r3,#25 @ upper ?
addle r6,r3,#65 @ yes compute ascci character
addgt r6,r3,#97 - 26 @ lower
strb r6,[r7,#9] @ store in message
mov r0,r1 @ convert count in decimal
ldr r1,iAdrsZoneConv
bl conversion10
ldr r0,iAdrszMessResult @ and display
bl affichageMess
ldr r0,iAdrsZoneConv
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
7:
add r3,r3,#1
cmp r3,#52
blt 6b
100:
pop {r1-r7,pc}
iAdrtabCptLetters: .int tabCptLetters
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../affichage.inc"
 
</syntaxhighlight>
{{Out}}
with the file unixdict.txt
<pre>
Program 32 bits start.
Result: a = 16421
Result: b = 4115
Result: c = 8216
Result: d = 5799
Result: e = 20144
Result: f = 2662
Result: g = 4129
Result: h = 5208
Result: i = 13980
Result: j = 430
Result: k = 1925
Result: l = 10061
Result: m = 5828
Result: n = 12097
Result: o = 12738
Result: p = 5516
Result: q = 378
Result: r = 13436
Result: s = 10210
Result: t = 12836
Result: u = 6489
Result: v = 1902
Result: w = 1968
Result: x = 617
Result: y = 3633
Result: z = 433
</pre>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">source: {
The Red Death had long devastated the country.
No pestilence had ever been so fatal, or so hideous.
Line 1,430 ⟶ 1,871:
]
 
inspect.muted frequencies</langsyntaxhighlight>
 
{{out}}
Line 1,461 ⟶ 1,902:
=={{header|AutoHotkey}}==
<br>This is the past version of this edit but made into a function, and now it only shows the letters that are in it, but not the ones with 0 letters
<langsyntaxhighlight AutoHotkeylang="autohotkey">LetterFreq(Var) {
Loop, 26
{
Line 1,474 ⟶ 1,915:
var2 := "foo bar"
Msgbox, % LetterFreq(var)
Msgbox, % LetterFreq(var2)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,508 ⟶ 1,949:
You can choose to use case sensitive search and if special chars should be searched too.
 
<syntaxhighlight lang="text">
Func _Letter_frequency($Path, $fcase = True, $fspecial_chars = True)
Local $hFile, $sRead, $iupto, $iStart, $iCount
Line 1,534 ⟶ 1,975:
If $iCount > 0 Then ConsoleWrite(Chr($iStart + $i) & " : " & $iCount & @CRLF)
Next
EndFunc ;==>_Letter_frequency</langsyntaxhighlight>
 
{{out}}
Line 1,550 ⟶ 1,991:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# usage: awk -f letters.awk HolyBible.txt
 
Line 1,556 ⟶ 1,997:
{ for(i=1;i<=NF;i++) m[$i]++}
END { for(i in m) printf("%9d %-14s\n", m[i],i) }
</syntaxhighlight>
</lang>
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="freebasic">txt$ = LOAD$("bible.txt")
 
FOR x = 97 TO 122
PRINT CHR$(x-32), " ", CHR$(x), " : ", COUNT(txt$, x-32), " - ", COUNT(txt$, x)
NEXT
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,596 ⟶ 2,037:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> DIM cnt%(255)
file% = OPENIN("C:\unixdict.txt")
Line 1,614 ⟶ 2,055:
FOR c% = &41 TO &5A
PRINT CHR$(c%)CHR$(c%+32) ": " cnt%(c%)+cnt%(c%+32)
NEXT</langsyntaxhighlight>
{{out}}
<pre>
Line 1,646 ⟶ 2,087:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let start() be
Line 1,667 ⟶ 2,108:
endread()
$)</langsyntaxhighlight>
{{out}}
<pre>Aa: 16421
Line 1,695 ⟶ 2,136:
Yy: 3633
Zz: 433</pre>
 
=={{header|BQN}}==
<code>"sample.txt"</code> can be substituted with any filename.
<syntaxhighlight lang="bqn">Freq←⍷≍/⁼∘⊐
 
Freq "balloon"
# For a file:
Freq •FLines "sample.txt"</syntaxhighlight>
<syntaxhighlight lang="text">┌─
╵ 'b' 'a' 'l' 'o' 'n'
1 1 2 2 1
┘</syntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">(lc=
counts c
. fil$(!arg,r) {open file for reading}
Line 1,714 ⟶ 2,167:
 
lc$"valid.bra" {example: count letters in Bracmat's validation suite.}
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="bracmat">107*A
+ 33*B
+ 37*C
Line 1,765 ⟶ 2,218:
+ 685*y
+ 211*z
+ 1035*i</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">/* declare array */
int frequency[26];
int ch;
Line 1,786 ⟶ 2,239:
else if ('A' <= ch && ch <= 'Z') /* upper case */
frequency[ch-'A']++;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.IO;
Line 1,825 ⟶ 2,278:
}
}
}</langsyntaxhighlight>
{{out}}
<pre> : 1
Line 1,840 ⟶ 2,293:
Declarative approach:
 
<langsyntaxhighlight lang="csharp">
var freq = from c in str
where char.IsLetter(c)
Line 1,849 ⟶ 2,302:
foreach(var g in freq)
Console.WriteLine(g);
</syntaxhighlight>
</lang>
<pre>
C:2
Line 1,862 ⟶ 2,315:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <fstream>
#include <iostream>
 
Line 1,887 ⟶ 2,340:
}
}
}</langsyntaxhighlight>
{{out}} when file contains "Hello, world!" (without quotes):
<pre>
Line 1,902 ⟶ 2,355:
 
=={{header|Clojure}}==
<langsyntaxhighlight Clojurelang="clojure">(println (sort-by second >
(frequencies (map #(java.lang.Character/toUpperCase %)
(filter #(java.lang.Character/isLetter %) (slurp "text.txt"))))))</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun letter-freq (file)
(with-open-file (stream file)
(let ((str (make-string (file-length stream)))
Line 1,918 ⟶ 2,371:
(if (zerop (rem i 8)) #\newline #\tab))))))
 
(letter-freq "test.lisp")</langsyntaxhighlight>
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
<lang COBOL>
IDENTIFICATION DIVISION.
PROGRAM-ID. Letter-Frequency.
Line 2,104 ⟶ 2,557:
END-PROGRAM.
</langsyntaxhighlight>
 
{{out}}
Line 2,128 ⟶ 2,581:
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE LetterFrecuency;
IMPORT Files,StdLog,Strings;
Line 2,173 ⟶ 2,626:
END Do;
END LetterFrecuency.
</syntaxhighlight>
</lang>
Execute: ^Q LetterFrecuency.Do<br/>
{{out}}
Line 2,206 ⟶ 2,659:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
include "argv.coh";
include "file.coh";
Line 2,251 ⟶ 2,704:
print_nl();
ch := ch + 1;
end loop;</langsyntaxhighlight>
 
{{out}}
Line 2,285 ⟶ 2,738:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.ascii, std.algorithm, std.range;
 
Line 2,295 ⟶ 2,748:
 
writefln("%(%(%s, %),\n%)", frequency[].chunks(10));
}</langsyntaxhighlight>
{{out}}
<pre>16421, 4115, 8216, 5799, 20144, 2662, 4129, 5208, 13980, 430,
Line 2,305 ⟶ 2,758:
 
=={{header|Draco}}==
<langsyntaxhighlight lang="draco">proc nonrec main() void:
file() infile;
[256] char linebuf;
Line 2,335 ⟶ 2,788:
writeln(c, pretend(i | 32, char), ": ", n:5)
od
corp</langsyntaxhighlight>
{{out}}
<pre>Aa: 16421
Line 2,363 ⟶ 2,816:
Yy: 3633
Zz: 433</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
len d[] 26
repeat
s$ = input
until s$ = ""
for c$ in strchars s$
c = strcode c$
if c >= 97 and c <= 122
c -= 32
.
if c >= 65 and c <= 91
d[c - 64] += 1
.
.
.
for i to 26
write strchar (96 + i) & ": "
print d[i]
.
input_data
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including
punctuation), but some only count letters A to Z.
Other tasks related to string operations:
</syntaxhighlight>
 
 
=={{header|EchoLisp}}==
We use a property list - plist for short - which is a hash table, to store the pairs ( letter . count) .
<langsyntaxhighlight lang="lisp">
;; bump count when letter added
(define (hash-counter hash key )
Line 2,378 ⟶ 2,859:
(map (curry hash-counter hash) (string->list string))
(list-sort hash-compare (symbol-plist hash)))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="lisp">
(define (file-stats file string)
(set-plist! 'file-stats null) ; reset counters
Line 2,405 ⟶ 2,886:
➛ Total letters: 212631
➛ Total lines: 4539
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
 
<langsyntaxhighlight Eiffellang="eiffel">class
APPLICATION
 
Line 2,449 ⟶ 2,930:
end
end
end</langsyntaxhighlight>
{{out}} when file contains "Hello, Eiffel world!":
<pre>H: 1
Line 2,463 ⟶ 2,944:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">file = hd(System.argv)
 
File.read!(file)
Line 2,471 ⟶ 2,952:
|> Enum.reduce(Map.new, fn c,acc -> Map.update(acc, c, 1, &(&1+1)) end)
|> Enum.sort_by(fn {_k,v} -> -v end)
|> Enum.each(fn {k,v} -> IO.puts "#{k} #{v}" end)</langsyntaxhighlight>
 
{{out}}
Line 2,503 ⟶ 2,984:
Q 378
</pre>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">
(defun tally-letter-frequency-in-file ()
"Open a file and count the number of times each letter appears."
(let ((alphabet "abcdefghijklmnopqrstuvwxyz") ; variable to hold letters we will be counting
(current-letter) ; variable to hold current letter we will be counting
(count) ; variable to count how many times current letter appears
(case-fold-search t)) ; ignores case
(find-file "~/Documents/Elisp/MobyDick.txt") ; open file in a buffer (or switch to buffer if file is already open)
(while (>= (length alphabet) 1) ; as long as there is at least 1 letter left in alphabet
(beginning-of-buffer) ; go to the beginning of the buffer
(setq current-letter (substring alphabet 0 1)) ; set current-letter to first letter of alphabet
(setq count (how-many current-letter)) ; count how many of this letter in file
(end-of-buffer) ; go to the end of the buffer
(insert (format "\n%s%s - %7d" current-letter (upcase current-letter) count)) ; write how many times that letter appears
(setq alphabet (substring alphabet 1 nil))) ; remove first letter from alphabet
(insert "\n")))
 
</syntaxhighlight>
{{out}}
<pre>
 
aA - 79220
bB - 17203
cC - 23318
dD - 38834
eE - 119345
fF - 21252
gG - 21287
hH - 63769
iI - 66671
jJ - 1176
kK - 8228
lL - 43349
mM - 23626
nN - 66778
oO - 70808
pP - 17873
qQ - 1581
rR - 53589
sS - 65136
tT - 89874
uU - 27205
vV - 8724
wW - 22556
xX - 1064
yY - 17242
zZ - 635
</pre>
 
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">%% Implemented by Arjun Sunel
-module(letter_frequency).
-export([main/0, letter_freq/1]).
Line 2,534 ⟶ 3,066:
end
end, lists:seq(0, 222)).
</syntaxhighlight>
</lang>
{{out}}
<pre>"\n" : 5
Line 2,558 ⟶ 3,090:
 
Alternatively letter_freq/1 above can be replaced with
<syntaxhighlight lang="erlang">
<lang Erlang>
letter_freq( Data ) ->
Dict = lists:foldl( fun (Char, Dict) -> dict:update_counter( Char, 1, Dict ) end, dict:new(), Data ),
[io:fwrite( "~p : ~p~n", [[X], dict:fetch(X, Dict)]) || X <- dict:fetch_keys(Dict)].
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
Using ERRE help file for testing.
<langsyntaxhighlight ERRElang="erre">PROGRAM LETTER
 
DIM CNT[255]
Line 2,591 ⟶ 3,123:
 
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
{{works with|OpenEuphoria}}
<langsyntaxhighlight lang="euphoria">
-- LetterFrequency.ex
-- Count frequency of each letter in own source code.
Line 2,620 ⟶ 3,152:
 
if getc(0) then end if
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,633 ⟶ 3,165:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let alphabet =
['A'..'Z'] |> Set.ofList
 
Line 2,647 ⟶ 3,179:
 
for (letter, freq) in res do
printfn "%A, %A" letter freq</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: hashtables locals io assocs kernel io.encodings.utf8 io.files formatting ;
IN: count-letters
 
Line 2,668 ⟶ 3,200:
utf8 [ count-from-stream ] with-file-reader
print-counts ;
</syntaxhighlight>
</lang>
 
=={{header|FBSL}}==
The result of the first evaluation of ASC() is retained in the symbol ASC for later use. This is a standard feature of FBSL functions. The ascii array is dynamic. Command(1) is the name of the script file.
 
<langsyntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
'Open a text file and count the occurrences of each letter.
Line 2,695 ⟶ 3,227:
 
PAUSE
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">create counts 26 cells allot
 
: freq ( filename -- )
Line 2,714 ⟶ 3,246:
loop ;
 
s" example.txt" freq</langsyntaxhighlight>
 
=={{header|Fortran}}==
Using the configuration file (which has changed since the example was documented) of the J example, compilation and output of this program on a gnu/linux system is
<langsyntaxhighlight lang="fortran">
-*- mode: compilation; default-directory: "/tmp/" -*-
Compilation started at Sat May 18 18:09:46
Line 2,727 ⟶ 3,259:
 
Compilation finished at Sat May 18 18:09:46
</syntaxhighlight>
</lang>
And here's the FORTRAN90 program source. The program reads stdin and writes the result to stdout. Future enhancement: use block size records.
<syntaxhighlight lang="fortran">
<lang FORTRAN>
! count letters from stdin
program LetterFrequency
Line 2,757 ⟶ 3,289:
write(6, *) a
end program LetterFrequency
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim a(65 to 90) As Integer ' array to hold frequency of each letter, all elements zero initially
Line 2,787 ⟶ 3,319:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 2,854 ⟶ 3,386:
 
How many other languages in this page do all or any of this correctly?
<langsyntaxhighlight lang="frink">print[formatTable[countToArray[select[graphemeList[lc[normalizeUnicode[read["https://www.gutenberg.org/files/135/135-0.txt", "UTF-8"],"NFC"]]], %r/[[:alpha:]]/ ]] , "right"]]</langsyntaxhighlight>
{{out}}
<pre>
Line 2,900 ⟶ 3,432:
ñ 2
</pre>
 
=={{header|FutureBasic}}==
A clone of the Objective-C solution.
 
This code assumes a text file named "MyTextFile.txt" is in the same folder as the code file.
<syntaxhighlight lang="futurebasic">include "NSLog.incl"
include resources "MyTextFile.txt"
 
void local fn DoIt
CFURLRef url
CFStringRef string
NSUInteger length, index
unichar chr
CountedSetRef set
CFNumberRef number
url = fn BundleURLForResource( fn BundleMain, @"MyTextFile", @"txt", NULL )
string = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )
if ( string )
set = fn CountedSetWithCapacity(0)
length = len(string)
for index = 0 to length - 1
chr = fn StringCharacterAtIndex( string, index )
CountedSetAddObject( set, @(chr) )
next
for number in set
NSLog(@"%C = %ld",intVal(number),fn CountedSetCountForObject( set, number ))
next
end if
end fn
 
fn DoIt
 
HandleEvents</syntaxhighlight>
 
=={{header|Gambas}}==
<langsyntaxhighlight lang="gambas">Public Sub Form_Open()
Dim sData As String = File.Load("data.txt")
Dim iCount, iSpaces, iLetters, iOther As Integer
Line 2,922 ⟶ 3,488:
Message("Text contains " & Len(sData) & " characters\n" & iLetters & " Letters\n" & iSpaces & " Spaces\n" & iOther & " Punctuation, newlines etc.")
 
End</langsyntaxhighlight>
Output:
<pre>
Line 2,932 ⟶ 3,498:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,988 ⟶ 3,554:
func (lfs lfList) Swap(i, j int) {
lfs[i], lfs[j] = lfs[j], lfs[i]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,036 ⟶ 3,602:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def frequency = { it.inject([:]) { map, value -> map[value] = (map[value] ?: 0) + 1; map } }
 
frequency(new File('frequency.groovy').text).each { key, value ->
println "'$key': $value"
}</langsyntaxhighlight>
{{out}}
<pre>'d': 1
Line 3,058 ⟶ 3,624:
 
=={{header|Harbour}}==
<langsyntaxhighlight lang="visualfoxpro">PROCEDURE Main()
LOCAL s := hb_MemoRead( Left( __FILE__ , At( ".", __FILE__ )) +"prg")
LOCAL c, n, i
Line 3,081 ⟶ 3,647:
END
 
RETURN</langsyntaxhighlight>
 
{{Out}} (counting the printable characters of its own source code):
Line 3,093 ⟶ 3,659:
=={{header|Haskell}}==
Short version:
<langsyntaxhighlight Haskelllang="haskell">import Data.List (group, sort)
 
import Control.Arrow ((&&&))
main :: IO ()
main = interact (show . map (head &&& length) . group . sort)</lang>
main = interact (show . fmap ((,) . head <*> length) . group . sort</syntaxhighlight>
 
or, as an alternative to sorting and grouping the whole string, we could use some kind of container as the accumulator for a single fold, for example:
 
<langsyntaxhighlight lang="haskell">import Data.List (sortBy)
import qualified Data.Map.Strict as M
import Data.Ord (comparing)
Line 3,116 ⟶ 3,683:
(flip $ comparing snd)
. M.toList
. charCounts</langsyntaxhighlight>
{{Out}}
<pre>(' ',516452)
Line 3,241 ⟶ 3,808:
=={{header|Icon}} and {{header|Unicon}}==
The example below counts (case insensitive) letters and was run on a version of this source file.
<langsyntaxhighlight Iconlang="icon">link printf
 
procedure main(A)
Line 3,261 ⟶ 3,828:
every c := key(T) do
printf("%s - %d\n",c,T[c])
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 3,288 ⟶ 3,855:
n - 28
v - 4</pre>
 
=={{header|Insitux}}==
Works with the Node REPL.
<syntaxhighlight lang="insitux">
(-> (read "README.md")
(filter letter?)
(map upper-case)
freqs
(sort-by 1)
reverse
(map (join " "))
(join " "))
</syntaxhighlight>
{{out}}
<pre>
E 2637 T 2238 R 1893 A 1880 N 1717 I 1676 O 1562 S 1469 L 1156 C 961 U 905 H 699 D 680 P 585 M 567 F 561 G 378 B 373 V 343 Y 324 X 263 W 220 K 134 Z 56 J 49 Q 18
</pre>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Letters.bas"
110 NUMERIC LETT(65 TO 90)
120 FOR I=65 TO 90
Line 3,311 ⟶ 3,895:
290 CLOSE #1
300 CONTINUE
310 END HANDLER</langsyntaxhighlight>
 
=={{header|J}}==
<br>Input is a directory-path with filename. Result is 26 integers representing counts of each letter, in alphabetic order (a's count is first).
 
<langsyntaxhighlight lang="j">ltrfreq=: 3 : 0
letters=. u: 65 + i.26 NB. upper case letters
<: #/.~ letters (, -. -.~) toupper fread y
)</langsyntaxhighlight>
 
Example use (based on [[Read_a_configuration_file|a configuration file from another task]]):
 
<langsyntaxhighlight lang="j"> ltrfreq 'config.file'
88 17 17 24 79 18 19 19 66 0 2 26 26 57 54 31 1 53 43 59 19 6 2 0 8 0</langsyntaxhighlight>
 
=={{header|Java}}==
This implementation will capture the frequency of all characters
<syntaxhighlight lang="java5">
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
</syntaxhighlight>
<syntaxhighlight lang="java5">
public static void main(String[] args) throws IOException {
Map<Integer, Integer> frequencies = frequencies("src/LetterFrequency.java");
System.out.println(print(frequencies));
}
 
static String print(Map<Integer, Integer> frequencies) {
StringBuilder string = new StringBuilder();
int key;
for (Map.Entry<Integer, Integer> entry : frequencies.entrySet()) {
key = entry.getKey();
string.append("%,-8d".formatted(entry.getValue()));
/* display the hexadecimal value for non-printable characters */
if ((key >= 0 && key < 32) || key == 127) {
string.append("%02x%n".formatted(key));
} else {
string.append("%s%n".formatted((char) key));
}
}
return string.toString();
}
 
static Map<Integer, Integer> frequencies(String path) throws IOException {
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(path))) {
/* key = character, and value = occurrences */
Map<Integer, Integer> map = new HashMap<>();
int value;
while ((value = reader.read()) != -1) {
if (map.containsKey(value)) {
map.put(value, map.get(value) + 1);
} else {
map.put(value, 1);
}
}
return map;
}
}
</syntaxhighlight>
<pre>
44 0a
463
1 !
8 "
5 %
2 &
33 (
33 )
4 *
1 +
9 ,
3 -
29 .
5 /
2 0
4 1
3 2
1 3
1 7
1 8
1 :
19 ;
7 <
12 =
7 >
2 B
4 E
4 F
2 H
18 I
2 K
2 L
8 M
3 O
3 R
13 S
1 V
1 [
1 ]
73 a
3 b
28 c
19 d
121 e
13 f
25 g
11 h
53 i
6 j
8 k
25 l
22 m
67 n
24 o
44 p
8 q
81 r
30 s
87 t
34 u
15 v
7 w
5 x
20 y
11 {
2 |
11 }
</pre>
<br />
{{works with|Java|5+}}
<langsyntaxhighlight lang="java5">import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Line 3,353 ⟶ 4,053:
System.out.println(Arrays.toString(countLetters("filename.txt")));
}
}</langsyntaxhighlight>
{{works with|Java|7+}}
In Java 7, we can use try with resources. The <code>countLetters</code> method would look like this:
<langsyntaxhighlight lang="java5">public static int[] countLetters(String filename) throws IOException{
int[] freqs = new int[26];
try(BufferedReader in = new BufferedReader(new FileReader(filename))){
Line 3,370 ⟶ 4,070:
}
return freqs;
}</langsyntaxhighlight>
{{works with|Java|8+}}
In Java 8, we can use streams. This code also handles unicode codepoints as well. The <code>countLetters</code> method would look like this:
<langsyntaxhighlight lang="java5">public static Map<Integer, Long> countLetters(String filename) throws IOException {
return Files.lines(Paths.get(filename))
.flatMapToInt(String::chars)
Line 3,379 ⟶ 4,079:
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 3,387 ⟶ 4,087:
we can still use core JavasScript (ES5 in the example below), to count the characters in a text once it has been read from a file system.
 
<langsyntaxhighlight JavaScriptlang="javascript">(function(txt) {
 
var cs = txt.split(''),
Line 3,415 ⟶ 4,115:
with a large party. Nothing could be more delightful! To be fond of\
dancing was a certain step towards falling in love; and very lively\
hopes of Mr. Bingley's heart were entertained."); </langsyntaxhighlight>
 
{{Out}}
 
<langsyntaxhighlight JavaScriptlang="javascript">[[" ", 121], ["!", 1], ["'", 1], [",", 13], ["-", 3], [".", 9], [";", 2],
["B", 3], ["H", 2], ["L", 2], ["M", 3], ["N", 2], ["S", 1], ["T", 2], ["W", 1],
["a", 53], ["b", 13], ["c", 17], ["d", 29], ["e", 82], ["f", 17], ["g", 16], ["h", 36],
["i", 44], ["j", 1], ["k", 3], ["l", 34], ["m", 11], ["n", 41], ["o", 40], ["p", 8],
["q", 2], ["r", 35], ["s", 39], ["t", 55], ["u", 20], ["v", 7], ["w", 17], ["x", 2], ["y", 16]]</langsyntaxhighlight>
 
===ES6===
Line 3,429 ⟶ 4,129:
Using the 'JavaScript for Automation' embedding of a JSContext on macOS, for access to the file system:
 
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 3,557 ⟶ 4,257:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[" ",516452]
Line 3,591 ⟶ 4,291:
["A",7359]
["œ",7121]
["",7033]
["H",6605]
["M",6208]
Line 3,684 ⟶ 4,384:
(note that this version omits the opening of a text file which is specified in the task description):
 
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 3,702 ⟶ 4,402:
null, 2
);
})();</langsyntaxhighlight>
 
Using the spread operator, you get the unicode characters rather than the UTF-16 code units.
Line 3,734 ⟶ 4,434:
 
=={{header|jq}}==
The following program will report the frequency of all characters in the input file, including newlines, returns, etc, provided the file will fit in memory.<langsyntaxhighlight lang="jq">
# Input: an array of strings.
# Output: an object with the strings as keys,
Line 3,745 ⟶ 4,445:
| keys | sort[] | [., $counter[.] ]
 
</syntaxhighlight>
</lang>
Example:<langsyntaxhighlight lang="sh">jq -s -R -c -f Letter_frequency.jq somefile.txt</langsyntaxhighlight>
{{Out}}
<pre>["\n",12]
Line 3,766 ⟶ 4,466:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using DataStructures
function letterfreq(file::AbstractString; fltr::Function=(_) -> true)
Line 3,773 ⟶ 4,473:
display(letterfreq("src/Letter_frequency.jl"; fltr=isletter))
</langsyntaxhighlight>{{out}}
<pre>
DataStructures.OrderedDict{Char,Int64} with 29 entries:
Line 3,799 ⟶ 4,499:
 
=={{header|K}}==
<langsyntaxhighlight Klang="k">+(?a;#:'=a:,/0:`)</langsyntaxhighlight>
 
Example: The file "hello.txt" contains the string "Hello, world!"
 
<langsyntaxhighlight Klang="k">
c:+(?a;#:'=a:,/0:`hello.txt)
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,823 ⟶ 4,523:
Sort on decreasing occurrences:
 
<syntaxhighlight lang="k">
<lang K>
c@>c[;1]
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,842 ⟶ 4,542:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.io.File
Line 3,852 ⟶ 4,552:
val sum = letterMap.values.sumBy { it.size }
println("\nTotal letters = $sum")
}</langsyntaxhighlight>
 
{{out}}
Line 3,891 ⟶ 4,591:
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
 
Line 3,910 ⟶ 4,610:
[[ ${ch} == ?(\S) ]] && print -- "${ch} ${freqCnt[${ch}]}"
done
</syntaxhighlight>
</lang>
{{out}}
Counts the characters of the source code file
Line 3,970 ⟶ 4,670:
In this entry we choose to show how lambdatalk can use any existing javascript code (say the #Javascript entry in this page), and build an interface to use it as a standard lambdatalk function. So, applied to any string the W.frequency primitive returns a pair structure containing the array of chars and the corresponding array of frequencies.
 
<syntaxhighlight lang="scheme">
<lang Scheme>
 
{script
Line 4,024 ⟶ 4,724:
 
 
</syntaxhighlight>
</lang>
 
=={{header|langur}}==
<syntaxhighlight lang="langur">val .countLetters = fn(.s) {
{{works with|langur|0.7.0}}
<lang langur>val .countLetters = f(.s) {
for[=h{}] .s2 in split(replace(.s, RE/\P{L}/)) {
_for[.s2; 0] += 1
Line 4,035 ⟶ 4,734:
 
val .counts = .countLetters(readfile "./fuzz.txt")
writeln join "\n", map ffn(.k) $"\.k;: \.counts[.k];", keys .counts</lang>
</syntaxhighlight>
 
{{out}}
Line 4,060 ⟶ 4,760:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(
str = 'Hello world!',
freq = map
Line 4,083 ⟶ 4,783:
with elem in #freq->keys do => {^
'"'+#elem+'": '+#freq->find(#elem)+'\r'
^}</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
Un-rem a line to convert to all-upper-case.
Letter freq'y is printed as percentages.
<syntaxhighlight lang="lb">
<lang lb>
open "text.txt" for input as #i
txt$ =input$( #i, lof( #i))
Line 4,109 ⟶ 4,809:
 
end
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
This solution counts letters only, which could be changed by altering the pattern argument to 'gmatch' on line 31. It also treats upper and lower case letters as distinct, which could be changed by changing everything to upper or lower case with string.upper() or string.lower() before tallying.
<langsyntaxhighlight lang="lua">-- Return entire contents of named file
function readFile (filename)
local file = assert(io.open(filename, "r"))
Line 4,143 ⟶ 4,843:
-- Main procedure
local letterCount = tally()
for letter in readFile(arg[1] or arg[0]):gmatch("%a") do
letterCount(letter)
end
for k, v in pairs(letterCount()) do
print(k, v)
end</langsyntaxhighlight>
Output from running this script on itself:
<pre>i 24
g 2
h 4
e 61
f 16
c 19
d 17
R 2
o 31
p 7
m 4
n 42
k 4
l 40
y 4
w 1
x 7
u 18
v 2
c 19
k 4
M 1
s 14
d 17
l 40
e 61
t 54
am 244
r 34
u 18
C 3
Mo 132
A 1
g 3
x 7
F 2
ry 32</pre>4
w 1
n 42
h 4
a 25
p 7</pre>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
document file1$={Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation), but some only count letters A to Z
Line 4,204 ⟶ 4,904:
print #Console, Export$
clipboard Export$
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,232 ⟶ 4,932:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">StringTools:-CharacterFrequencies(readbytes("File.txt",infinity,TEXT))</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
 
<langsyntaxhighlight Mathematicalang="mathematica">Tally[Characters[Import["file.txt","Text"]]]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function u = letter_frequency(t)
if ischar(t)
t = abs(t);
Line 4,245 ⟶ 4,945:
A = sparse(t+1,1,1,256,1);
printf('"%c":%i\n',[find(A)-1,A(A>0)]')
end</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">// define a list to hold characters and amounts
characters = list()
amounts = list()
Line 4,285 ⟶ 4,985:
for i in range(0, len(characters) - 1)
println format("%-20s %d", characters[i], amounts[i])
end for</langsyntaxhighlight>
{{out}}
<pre>$ java -jar ../nanoquery-2.3_1462.jar -b letterfreq.nq sherlock-holmes.txt
Line 4,329 ⟶ 5,029:
=={{header|NetRexx}}==
{{trans|REXX}}
<langsyntaxhighlight lang="netrexx">/* NetRexx ************************************************************
* 22.05.2013 Walter Pachl translated from REXX
**********************************************************************/
Line 4,408 ⟶ 5,108:
end
 
return fileLines</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import tables, os
 
var t = initCountTable[char]()
Line 4,417 ⟶ 5,117:
for c in l:
t.inc(c)
echo t</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
use IO;
 
Line 4,451 ⟶ 5,151:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
 
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
int main (int argc, const char *argv[]) {
Line 4,475 ⟶ 5,175:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 4,481 ⟶ 5,181:
We open a text file and compute letter frequency. Other characters than [a-z] and [A-Z] are ignored, and upper case letters are first converted to lower case before to compute letter frequency.
 
<langsyntaxhighlight lang="ocaml">let () =
let ic = open_in Sys.argv.(1) in
let base = int_of_char 'a' in
Line 4,495 ⟶ 5,195:
for i=0 to 25 do
Printf.printf "%c -> %d\n" (char_of_int(i + base)) arr.(i)
done</langsyntaxhighlight>
 
If we want to compute all characters in an UTF8 file, we must use an external library, for example Batteries. The following function takes as input a string that contains the path to the file, and prints all the characters together with their frequencies, ordered by increasing frequencies, on the standard output.
 
<langsyntaxhighlight lang="ocaml">
open Batteries
 
Line 4,510 ⟶ 5,210:
@@ List.sort (fun (_,v) (_,v') -> compare v v')
@@ Hashtbl.fold (fun k v l -> (Text.of_uchar k,v) :: l) freq []
</syntaxhighlight>
</lang>
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(define source (bytes->string (file->bytestream "letter_frequency.scm"))) ; utf-8
(define dict (lfold (lambda (ff char)
Line 4,539 ⟶ 5,239:
(print))
(ff->alist dict))
</syntaxhighlight>
</lang>
{{Out}}
<pre>NEWLINE --> 27
Line 4,604 ⟶ 5,304:
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
indexbase 0
 
Line 4,626 ⟶ 5,326:
print pr
'putfile "CharCount.txt",pr
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">v=vector(26);
U=readvec("foo.txt");
for(i=1,#U,u=Vecsmall(U[i]);for(j=1,#u,if(u[j]>64&&u[j]<91,v[u[j]-64]++,u[j]>96&&u[j]<123,v[u[j]-96]++)));
v</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Extended Pascal}}
<langsyntaxhighlight lang="pascal">program letterFrequency(input, output);
var
chart: array[char] of 0..maxInt value [otherwise 0];
Line 4,649 ⟶ 5,349:
{ now, chart[someLetter] gives you the letter’s frequency }
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
Counts letters in files given on command line or piped to stdin. Case insensitive.
<langsyntaxhighlight lang="perl">while (<>) { $cnt{lc chop}++ while length }
print "$_: ", $cnt{$_}//0, "\n" for 'a' .. 'z';</langsyntaxhighlight>
 
=={{header|Phix}}==
<del>Counts own source or supplied filename</del> Now counts words in unixdict.txt of 17 letters or more (to make it js compatible)
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">lc</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#7E</span><span style="color: #0000FF;">)</span>
Line 4,678 ⟶ 5,378:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,686 ⟶ 5,386:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">0 255 repeat var ascCodes
 
"unixdict.txt" "r" fopen var file
Line 4,719 ⟶ 5,419:
endfor
file fclose
endif</langsyntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
print_r(array_count_values(str_split(file_get_contents($argv[1]))));
?></langsyntaxhighlight>
 
=={{header|Picat}}==
Sorting on the frequency (decreasing).
<langsyntaxhighlight Picatlang="picat">go =>
% removing '\n' first
Chars = delete_all(read_file_chars("unixdict.txt"),'\n'),
Line 4,744 ⟶ 5,444:
sort_map(Map,values) = [K=V:_=(K=V) in sort([V=(K=V): K=V in Map])].
sort_map(Map,keys) = sort([KV : KV in Map]).
sort_map(Map) = sort_map(Map,keys).</langsyntaxhighlight>
 
{{out}}
Line 4,753 ⟶ 5,453:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let Freq NIL
(in "file.txt"
(while (char) (accu 'Freq @ 1)) )
(sort Freq) )</langsyntaxhighlight>
For a "file.txt":
<pre>abcd
Line 4,764 ⟶ 5,464:
 
=={{header|Pike}}==
<syntaxhighlight lang="pike">
<lang Pike>
string all = Stdio.read_file("README.md");
mapping res = ([]);
Line 4,770 ⟶ 5,470:
res[char]++;
write("%O\n", res);
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 4,804 ⟶ 5,504:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">
frequencies: procedure options (main);
declare tallies(26) fixed binary static initial ((26) 0);
Line 4,828 ⟶ 5,528:
put skip list (substr(alphabet, i, 1), tallies(i));
end;
end frequencies;</langsyntaxhighlight>
Data:
<pre>
Line 4,866 ⟶ 5,566:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function frequency ($string) {
$arr = $string.ToUpper().ToCharArray() |where{$_ -match '[A-KL-Z]'}
Line 4,876 ⟶ 5,576:
$file = "$($MyInvocation.MyCommand.Name )" #Put the name of your file here
frequency $(get-content $file -Raw)
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 4,912 ⟶ 5,612:
Only alphabetic codes are computed in uppercase state. <br>
Uses '''packlist/2''' defined there : [[Run-length encoding#Prolog]] <br>
<langsyntaxhighlight Prologlang="prolog">frequency(File) :-
read_file_to_codes(File, Code, []),
 
Line 4,965 ⟶ 5,665:
run(Var,[Other|RRest], [1,Var],[Other|RRest]):-
dif(Var,Other).
</syntaxhighlight>
</lang>
{{out}} for this file
<pre>Number of A : 63
Line 4,984 ⟶ 5,684:
=={{header|PureBasic}}==
Alphabetic codes are converted to uppercase before being used and no other codes are used as part of the calculations. <br>
<langsyntaxhighlight PureBasiclang="purebasic">Procedure countLetters(Array letterCounts(1), textLine.s)
;counts only letters A -> Z, uses index 0 of letterCounts() to keep a total of all counts
Protected i, lineLength = Len(textLine), letter
Line 5,024 ⟶ 5,724:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>File: D:\_T\Text\dictionary.txt
Line 5,062 ⟶ 5,762:
====Using collections.Counter====
{{works with|Python|2.7+ and 3.1+}}
<langsyntaxhighlight lang="python">import collections, sys
 
def filecharcount(openfile):
Line 5,068 ⟶ 5,768:
 
f = open(sys.argv[1])
print(filecharcount(f))</langsyntaxhighlight>
 
====As a fold====
Character counting can be conveniently expressed in terms of fold/reduce. See the example below, which also generates column-wrapped output:
{{Works with|Python|3}}
<langsyntaxhighlight lang="python">'''Character counting as a fold'''
 
from functools import reduce
Line 5,238 ⟶ 5,938:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Descending order of frequency:
Line 5,260 ⟶ 5,960:
===Procedural===
====Without using collections.Counter====
<langsyntaxhighlight lang="python">import string
if hasattr(string, 'ascii_lowercase'):
letters = string.ascii_lowercase # Python 2.2 and later
Line 5,283 ⟶ 5,983:
lettercounts = countletters(sourcedata)
for i in xrange(len(lettercounts)):
print "%s=%d" % (chr(i + ord('a')), lettercounts[i]),</langsyntaxhighlight>
 
This example defines the function and provides a sample usage. The ''if ... __main__...'' line allows it to be cleanly imported into any other Python code while also allowing it to function as a standalone script. (A very common Python idiom).
Line 5,291 ⟶ 5,991:
====Using defaultdict====
{{works with|Python|2.5+ and 3.x}}
<langsyntaxhighlight lang="python">...
from collections import defaultdict
def countletters(file_handle):
Line 5,302 ⟶ 6,002:
c = char.lower()
results[c] += 1
return results</langsyntaxhighlight>
 
Which eliminates the ungainly fiddling with ordinal values and offsets in function countletters of a previous example above. More importantly it allows the results to be more simply printed using:
 
<langsyntaxhighlight lang="python">lettercounts = countletters(sourcedata)
for letter,count in lettercounts.iteritems():
print "%s=%s" % (letter, count),</langsyntaxhighlight>
 
Again eliminating all fussing with the details of converting letters into list indices.
Line 5,314 ⟶ 6,014:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ [] 26 times [ 0 join ] ] is makecountnest ( --> [ )
 
[ char A char Z 1+ within ] is ischar ( c --> b )
Line 5,338 ⟶ 6,038:
join fail ]
countchars
echocount ] is fileletters ( $ --> )</langsyntaxhighlight>
 
'''Testing in Quackery shell:'''
Line 5,386 ⟶ 6,086:
=={{header|Quick Basic/QBASIC/PDS 7.1/VB-DOS}}==
This version counts valid letters from A to Z (including Ñ in Spanish alphabet) or characters in a file. Takes in account accented vowels. It runs in QB, QBASIC, PDS 7.1 and VB_DOS as is.
<syntaxhighlight lang="vb">
<lang VB>
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' Program CountCar '
Line 5,628 ⟶ 6,328:
' ---End of main program cycle
 
</syntaxhighlight>
</lang>
 
Output:
Line 5,657 ⟶ 6,357:
=={{header|R}}==
===Using summary===
<langsyntaxhighlight lang="rsplus">letter.frequency <- function(filename)
{
file <- paste(readLines(filename), collapse = '')
chars <- strsplit(file, NULL)[[1]]
summary(factor(chars))
}</langsyntaxhighlight>
 
Usage on itself:
 
<langsyntaxhighlight lang="rsplus">> source('letter.frequency.r')
> letter.frequency('letter.frequency.r')
- , . ' ( ) [ ] { } < = 1 a c d e f h i l L m n N o p q r s t u U y
22 3 2 1 2 6 6 2 2 1 1 3 1 1 9 6 1 14 7 2 7 8 3 4 6 1 3 3 1 8 8 7 3 1 2 </langsyntaxhighlight>
===Using table===
R's table function is more idiomatic. For variety, we will use read.delim rather than readLines and show how to only count letters. It is worth noting that readLines is prone to counting empty lines. This may be undesirable.
<langsyntaxhighlight lang="rsplus">letterFreq <- function(filename, lettersOnly)
{
txt <- read.delim(filename, header = FALSE, stringsAsFactors = FALSE, allowEscapes = FALSE, quote = "")
count <- table(strsplit(paste0(txt[,], collapse = ""), ""))
if(lettersOnly) count[names(count) %in% c(LETTERS, letters)] else count
}</langsyntaxhighlight>
{{out}}
For fun, we'll use this page for input. However, HTML rarely parses well and the variety of text here is so large that I suspect inaccurate output.
Line 5,690 ⟶ 6,390:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 5,699 ⟶ 6,399:
 
(letter-frequencies (open-input-string "abaabdc"))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,707 ⟶ 6,407:
 
Using input from a text file:
<langsyntaxhighlight lang="racket">
(letter-frequencies (open-input-file "somefile.txt"))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 5,734 ⟶ 6,434:
</div>
 
<syntaxhighlight lang="raku" perl6line>.&ws.say for slurp.comb.Bag.sort: -*.value;
 
sub ws ($pair) {
Line 5,742 ⟶ 6,442:
?? ($pair.key.uniname => $pair.value)
!! $pair
}</langsyntaxhighlight>
{{Out|Output when fed the same Les Misérables text file as used in the [[Word_frequency#Raku|Word frequency]] task}}
<pre>SPACE => 522095
Line 5,861 ⟶ 6,561:
 
=={{header|Raven}}==
<langsyntaxhighlight Ravenlang="raven">define count_letters use $words
{ } as $wordHash [ ] as $keys [ ] as $vals
$words each chr
Line 5,873 ⟶ 6,573:
"test.dat" as $file
$file read as $all_data
$all_data count_letters</langsyntaxhighlight>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
, <Arg 1>: {
= <Prout 'No filename given'>;
e.File, <ReadFile 1 e.File>: e.Text,
<Tally e.Text>: e.Counts
= <ShowLetterCounts (e.Counts) <Letters>>;
};
};
 
Letters {
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
};
 
ShowLetterCounts {
(e.T) = ;
(e.T) s.L e.Ls,
<Upper s.L>: s.UL, <Item (e.T) s.UL>: s.ULN,
<Lower s.L>: s.LL, <Item (e.T) s.LL>: s.LLN,
<+ s.ULN s.LLN>: s.Total
= <Prout s.UL s.LL ': ' <Symb s.Total>>
<ShowLetterCounts (e.T) e.Ls>;
};
 
ReadFile {
s.Chan e.Filename =
<Open 'r' s.Chan e.Filename>
<ReadFile (s.Chan)>;
(s.Chan), <Get s.Chan>: {
0 = <Close s.Chan>;
e.Line = e.Line '\n' <ReadFile (s.Chan)>;
};
};
 
Tally {
(e.T) = e.T;
(e.T) s.X e.Xs = <Tally (<Inc (e.T) s.X>) e.Xs>;
e.Xs = <Tally () e.Xs>;
}
 
Inc {
(e.1 (s.I s.N) e.2) s.I = e.1 (s.I <+ 1 s.N>) e.2;
(e.X) s.I = e.X (s.I 1);
};
 
Item {
(e.1 (s.I s.N) e.2) s.I = s.N;
(e.X) s.I = 0;
};</syntaxhighlight>
{{out}}
The result of running the program on its own source file:
<pre>Aa: 22
Bb: 2
Cc: 16
Dd: 5
Ee: 75
Ff: 10
Gg: 5
Hh: 11
Ii: 26
Jj: 1
Kk: 1
Ll: 49
Mm: 8
Nn: 33
Oo: 18
Pp: 6
Qq: 1
Rr: 17
Ss: 55
Tt: 44
Uu: 14
Vv: 2
Ww: 5
Xx: 12
Yy: 7
Zz: 1</pre>
=={{header|REXX}}==
===version 1===
Line 5,890 ⟶ 6,667:
 
All characters are still counted, whether a letter or not, including non-displayable characters.
<langsyntaxhighlight lang="rexx">/*REXX program counts the occurrences of all characters in a file, and note that all */
/* Latin alphabet letters are uppercased for also counting {Latin} letters (both cases).*/
/*════════════════════════════════════~~~~~~~~~~════════════════════════════════════════*/
Line 5,931 ⟶ 6,708:
say /*not a good place for dithering: ░▒▓█ */
say pad pad9 '☼ end─of─list ☼' /*show we are at the end of the list. */
/*§§§§ Talk about a mishmash of 2¢ comments. ▬▬^▬▬ stick a fork in it, we're all done. ☻*/</langsyntaxhighlight>
'''output''' &nbsp; when using the (above) REXX program for the input file:
 
Line 6,107 ⟶ 6,884:
 
===Version 2 (for TSO)===
<langsyntaxhighlight lang="rexx">/*REXX program counts the occurences of all characters in a file
* Adapted version 1 for TSO (EXECIO instead of linein)
* No translation to uppercase takes place
Line 6,167 ⟶ 6,944:
end
end
say 'file -----' dsn "----- has" other 'other characters.'</langsyntaxhighlight>
Output:
<pre>
Line 6,196 ⟶ 6,973:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
textData = read("C:\Ring\ReadMe.txt")
ln =len(textData)
Line 6,211 ⟶ 6,988:
if charCount[i] > 0 see char(i) + " = " + charCount[i] + " " + (charCount[i]/totCount)*100 + " %" + nl ok
next
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
« → text
« { 26 } 0 CON
1 text SIZE '''FOR''' j
text j DUP SUB NUM
'''IF''' DUP 97 ≥ OVER 122 ≤ AND '''THEN''' 32 - '''END'''
'''IF''' DUP 65 ≥ OVER 90 ≤ AND '''THEN''' 64 - DUP2 GET 1 + PUT '''ELSE''' DROP '''END'''
'''NEXT'''
{ }
1 26 '''FOR''' j
'''IF''' OVER j GET '''THEN''' LASTARG j 64 + CHR →TAG + '''END'''
'''NEXT''' SWAP DROP
» » '<span style="color:blue">AZFREQ</span>' STO
 
'<span style="color:blue">AZFREQ</span>' DUP RCL →STR SWAP EVAL <span style="color:grey">@ have the program count its own letters</span>
{{out}}
<pre>
1: { :A: 5 :B: 1 :C: 2 :D: 9 :E: 17 :F: 5 :G: 4 :H: 4 :I: 4 :J: 5 :L: 1 :M: 1 :N: 12 :O: 6 :P: 5 :R: 7 :S: 3 :T: 16 :U: 7 :V: 3 :X: 5 :Z: 1 }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def letter_frequency(file)
letters = 'a' .. 'z'
File.read(file) .
Line 6,223 ⟶ 7,020:
end
 
letter_frequency(ARGV[0]).sort_by {|key, val| -val}.each {|pair| p pair}</langsyntaxhighlight>
example output, using the program file as input:
<pre>$ ruby letterFrequency.rb letterFrequency.rb
Line 6,251 ⟶ 7,048:
 
===Ruby 2.0===
<langsyntaxhighlight lang="ruby">def letter_frequency(file)
freq = Hash.new(0)
file.each_char.lazy.grep(/[[:alpha:]]/).map(&:upcase).each_with_object(freq) do |char, freq_map|
Line 6,260 ⟶ 7,057:
letter_frequency(ARGF).sort.each do |letter, frequency|
puts "#{letter}: #{frequency}"
end</langsyntaxhighlight>
 
note that this version *should* use less memory, even on a gigantic file. This is done by using lazy enumerables, which ruby 2.0 introduces.
Line 6,312 ⟶ 7,109:
===Ruby 2.7===
Ruby 2.7 introduced "tally", which delivers a tally on anything enumerable.
<langsyntaxhighlight lang="ruby">p File.open("/usr/share/dict/words","r").each_char.tally</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">open "c:\rbp101\public\textFile.txt" for input as #f
textData$ = input$(#f, lof( #f))
ln =len(textData$)
Line 6,330 ⟶ 7,127:
for i = 32 to 255
if charCount(i) > 0 then print "Ascii:";using("###",i);" char:";chr$(i);" Count:";using("#######",charCount(i));" ";using("##.#",(charCount(i) / totCount) * 100);"%"
next i</langsyntaxhighlight>
 
Output uses this program to count itself:
Line 6,383 ⟶ 7,180:
=={{header|Rust}}==
Works with all UTF-8 characters
<langsyntaxhighlight lang="rust">use std::collections::btree_map::BTreeMap;
use std::{env, process};
use std::io::{self, Read, Write};
Line 6,417 ⟶ 7,214:
writeln!(&mut io::stderr(), "{}", msg).expect("Could not write to stderr");
process::exit(code)
}</langsyntaxhighlight>
 
Output when run on source file:
Line 6,490 ⟶ 7,287:
=={{header|S-BASIC}}==
Because S-BASIC lacks an EOF function, some extra care is required to avoid reading beyond the end of file. (CP/M text files are normally terminated with a Ctrl-Z byte, but not all text editors enforce this convention if the file would otherwise end on a sector boundary.)
<syntaxhighlight lang="s-basic">
<lang S-BASIC>
$constant EOF = 1AH rem normal end-of-file marker
 
Line 6,566 ⟶ 7,363:
9_exit
end
</syntaxhighlight>
</lang>
{{out}}
With Lincoln's Second Inaugural Address used as input
Line 6,601 ⟶ 7,398:
=={{header|Scala}}==
 
<langsyntaxhighlight lang="scala">import io.Source.fromFile
 
def letterFrequencies(filename: String) =
fromFile(filename).mkString groupBy (c => c) mapValues (_.length)</langsyntaxhighlight>
 
=={{header|Scheme}}==
Line 6,612 ⟶ 7,409:
Note that this prints the scheme representations of characters in no particular order.
 
<langsyntaxhighlight lang="scheme">(use-modules (ice-9 format))
 
(define (char-freq port table)
Line 6,632 ⟶ 7,429:
(format-table (char-freq (open-input-file filename) '())))
 
(print-freq "letter-frequency.scm")</langsyntaxhighlight>
 
Output when reading own source:
Line 6,675 ⟶ 7,472:
An implementation for CHICKEN scheme:
 
<langsyntaxhighlight lang="scheme">
(with-input-from-string "foobar"
(lambda ()
Line 6,684 ⟶ 7,481:
'()
read-char)))
</syntaxhighlight>
</lang>
 
which shows: ((#\f . 1) (#\o . 2) (#\b . 1) (#\a . 1) (#\r . 1))
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const type: charHash is hash [char] integer;
Line 6,710 ⟶ 7,507:
writeln(ch <& " " <& numberOfChars[ch]);
end for;
end func;</langsyntaxhighlight>
 
Output when the program uses itself as input:
Line 6,732 ⟶ 7,529:
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">
put file "~/Documents/addresses.csv" into source
 
Line 6,744 ⟶ 7,541:
put char 1 of theChar & " —> " & count
end repeat
</syntaxhighlight>
</lang>
Output:
<pre>
Line 6,823 ⟶ 7,620:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func letter_frequency(File file) {
file.read.chars.grep{.match(/[[:alpha:]]/)} \
.group_by {|letter| letter.downcase} \
Line 6,831 ⟶ 7,628:
var top = letter_frequency(File(__FILE__))
top.each{|pair| say "#{pair[0]}: #{pair[1]}"}</langsyntaxhighlight>
{{out}}
<pre>
Line 6,860 ⟶ 7,657:
=={{header|SIMPOL}}==
Example: open a text file and compute letter frequency.
<langsyntaxhighlight lang="simpol">constant iBUFSIZE 500
 
function main(string filename)
Line 6,902 ⟶ 7,699:
end while
end if
end function s</langsyntaxhighlight>
 
As this was being created I realized that in [SIMPOL] I wouldn't have done it this way (in fact, I wrote it differently the first time and had to go back and change it to use an array afterward). In [SIMPOL] we would have used the set object. It acts similarly to a single-dimensional array, but can also use various set operations, such as difference, unite, intersect, etc. One of th einteresting things is that each unique value is stored only once, and the number of duplicates is stored with it. The sample then looks a little cleaner:
 
<langsyntaxhighlight lang="simpol">constant iBUFSIZE 500
 
function main(string filename)
Line 6,942 ⟶ 7,739:
end while
end if
end function s</langsyntaxhighlight>
 
The final stage simply reads the totals for each character. One caveat, if a character is unrepresented, then it will not show up at all in this second implementation.
Line 6,949 ⟶ 7,746:
Make it a bag of characters and get the counts:
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">bagOfChars := 'someFile' asFilename contentsAsString asBag.
bag sortedCounts
select:[:assoc | assoc value isLetter ]
thenDo:[:assoc | assoc printCR].</langsyntaxhighlight>
If the file is huge, you may not want to read it in as a big string first, but feed the chars linewise into the bag:
<langsyntaxhighlight lang="smalltalk">bagOfChars := Bag new.
'someFile' asFilename readingLinesDo:[:eachLine | bagOfChars addAll:eachLine].
bag sortedCounts ...</langsyntaxhighlight>
 
To show all counts (as opposed to selecting the letter counts only), replace the "select:thenDo:" by a simple "do:", as in:
<langsyntaxhighlight lang="smalltalk">bag sortedCounts do:[:assoc | assoc printCR].</langsyntaxhighlight>
or even shorter:
<syntaxhighlight lang ="smalltalk">bag sortedCounts do:#printCR.</langsyntaxhighlight>
{{out}}
<pre>27->e
Line 6,970 ⟶ 7,767:
...</pre>
If you prefer seeing the character first, followed by the count, replace the do-loop's action with:
<langsyntaxhighlight lang="smalltalk">... do:[:assoc | '%s -> %s\n' printf:{assoc value . assoc key} on:Stdout ].</langsyntaxhighlight>
{{out}}
<pre>e -> 27
Line 6,980 ⟶ 7,777:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">import Foundation
 
let dictPath: String
Line 6,998 ⟶ 7,795:
for (char, count) in counts {
print("\(char): \(count)")
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc letterHistogram {fileName} {
# Initialize table (in case of short texts without every letter)
for {set i 97} {$i<=122} {incr i} {
Line 7,019 ⟶ 7,816:
}
 
letterHistogram the/sample.txt</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
words = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
Line 7,045 ⟶ 7,842:
 
*{frequency}
</syntaxhighlight>
</lang>
Output:
<pre style='height:30ex;overflow:scroll'>
Line 7,093 ⟶ 7,890:
===TXR Extraction Language plus TXR Lisp===
 
<langsyntaxhighlight lang="txr">@(do (defvar h (hash :equal-based)))
@(repeat)
@(coll :vars ())@\
Line 7,101 ⟶ 7,898:
@(end)
@(do (dohash (key value h)
(format t "~a: ~a\n" key value)))</langsyntaxhighlight>
 
{{out}}
Line 7,116 ⟶ 7,913:
===TXR Lisp===
 
<langsyntaxhighlight lang="txrlisp">(let* ((s (open-file "/usr/share/dict/words" "r"))
(chrs [keep-if* chr-isalpha (gun (get-char s))])
(h [group-reduce (hash) chr-toupper (op succ @1) chrs 0]))
(dohash (key value h)
(put-line `@key: @value`)))</langsyntaxhighlight>
 
=={{header|Vala}}==
{{libheader|Gee}}
Counts every character except new line character.
<langsyntaxhighlight lang="vala">
using Gee;
 
Line 7,146 ⟶ 7,943:
}
}
</syntaxhighlight>
</lang>
 
Sample output (run on its own source code) with several lines omitted:
Line 7,163 ⟶ 7,960:
=={{header|VBA}}==
 
<syntaxhighlight lang="vba">
<lang VBA>
Public Sub LetterFrequency(fname)
'count number of letters in text file "fname" (ASCII-coded)
Line 7,203 ⟶ 8,000:
Close
End Sub
</syntaxhighlight>
</lang>
 
Output:
Line 7,238 ⟶ 8,035:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
filepath = "SPECIFY FILE PATH HERE"
 
Line 7,263 ⟶ 8,060:
Set objfso = Nothing
Set objdict = Nothing
</syntaxhighlight>
</lang>
 
=={{header|Vedit macro language}}==
 
<langsyntaxhighlight lang="vedit">File_Open("c:\txt\a_text_file.txt")
Update()
 
Line 7,274 ⟶ 8,071:
#2 = Search(@103, BEGIN+ALL+NOERR)
Message(@103) Num_Type(#2)
}</langsyntaxhighlight>
 
Example output:
Line 7,306 ⟶ 8,103:
</pre>
 
=={{header|V (Vlang)}}==
 
<syntaxhighlight lang="v (vlang)">import os
struct LetterFreq {
rune int
Line 7,336 ⟶ 8,133:
println('${u8(f.rune).ascii_str()} ${f.rune} $f.freq')
}
}</langsyntaxhighlight>
{{out}}
 
Line 7,385 ⟶ 8,182:
=={{header|Whitespace}}==
 
<langsyntaxhighlight Whitespacelang="whitespace">
 
Line 7,438 ⟶ 8,235:
 
 
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="asm">push 127
; Initialize a slot in the heap for each ASCII character.
0:
Line 7,490 ⟶ 8,287:
4:
pop
exit</langsyntaxhighlight>
 
{{out}}
Line 7,502 ⟶ 8,299:
{{libheader|Wren-fmt}}
As we have a copy to hand, we count the number of letters in the MIT 10000 word list which apparently contains nothing other than lower case letters.
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File
import "./fmt" for Fmt
 
var text = File.read("mit10000.txt")
Line 7,523 ⟶ 8,320:
Fmt.print(" $5d 100.00", totalFreq)
 
Fmt.print("\nTotal characters in text file = $d minus 10000 \\n's = $d", text.count, totalFreq)</langsyntaxhighlight>
 
{{out}}
Line 7,569 ⟶ 8,366:
character ($1A). Usage: count <filename.ext
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int A(256), C, I;
[for C:= 0 to 256-1 do A(C):= 0;
Line 7,587 ⟶ 8,384:
if (I&7) = 7 then [CrLf(0); C:= C-8*16+1];
];
]</langsyntaxhighlight>
 
Example output of count.xpl counting itself:
Line 7,593 ⟶ 8,390:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">dim ascCodes(255)
 
f = open("unixdict.txt", "r")
Line 7,610 ⟶ 8,407:
next
close #f
end if</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn ccnt(textInBitBucket){
letters:=["a".."z"].pump(List().write,0); // array of 26 zeros
textInBitBucket.howza(0).pump(Void,'wrap(c){ // pump text as ints
Line 7,628 ⟶ 8,425:
 
ccnt(Data(0,Int,"This is a test"));
ccnt(File("dict.txt").read());</langsyntaxhighlight>
{{out}}
<pre>
Line 7,639 ⟶ 8,436:
 
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
<lang Zoea>
program: letter_frequency
input: 'cbcacb' # can be literal value, stdin or file url at runtime
derive: [[a,1],[b,2],[c,3]]
output: 'a : 1\nb : 2\nc : 3\n'
</syntaxhighlight>
</lang>
 
=={{header|Zoea Visual}}==
2,093

edits