RosettaCodeData/Task/Letter-frequency/S-BASIC/letter-frequency.basic

76 lines
1.7 KiB
Plaintext

$constant EOF = 1AH rem normal end-of-file marker
rem Convert character to upper case
function upcase(ch = char) = char
if ch >= 'a' and ch <= 'z' then
ch = ch - 32
end = ch
rem Convert string to all upper case characters
function allcaps(source = string) = string
var p = integer
for p = 1 to len(source) do
mid(source,p,1) = upcase(mid(source,p,1))
next p
end = source
comment
Preserve console and printer channels (#0 and #1)
Channel #2 declared as sequential ASCII
end
files d, d, sa(1)
var ch = char
var i = integer
based errcode = integer
base errcode at 103H rem S-BASIC stores run-time error code here
var filename = string
var total = real
dim real freq(26)
input "Name of text file to process: "; filename
filename = allcaps(filename)
open #2; filename
on error goto 7_trap rem In case input file lacks terminating ^Z
rem Initialize letter counts to zero
for i = 1 to 26
freq(i) = 0
next i
rem Process the file
total = 0
input3 #2; ch
while ch <> EOF do
begin
ch = upcase(ch);
if ch >= "A" and ch <= "Z" then
begin
freq(ch - 64) = freq(ch - 64) + 1
total = total + 1
end
input3 #2; ch
end
goto 8_done rem Jump around error trap
7_trap if errcode <> 15 then
begin
print "Runtime error = ";errcode
goto 9_exit
end
rem otherwise fall through on attempted read past EOF (err = 15)
8_done
close #2
rem Report results
print "Letter Count Percent"
for I = 1 to 26
print chr(i+64);" ";
print using " ##,###"; freq(i);
print using " ##.#"; freq(i) / total * 100
next i
9_exit
end