Seed7 
 FAQ 
 Manual 
 Screenshots 
 Examples 
 Algorithms 
 Download 
 Links 

 Examples 
 echo args 
 declare stmt 
 template 
 operator 
 file in string 
 simple clock 
 count words 
 subtype 
 Examples 
Count the words in a file
 previous   up   next 

This example counts the words in a file and writes a list with words and the coresponding count

 $ include "seed7_05.s7i";       # Standard Seed7 library
   include "scanfile.s7i";       # Import the getSimpleSymbol function

 const type: wordHash is hash [string] integer;

 const proc: main is func
   local
     var wordHash: numberOfWords is wordHash.EMPTY_HASH;
     var string: symbol is "";
   begin
     while not eof(IN) do
       symbol := getSimpleSymbol(IN);
       if symbol in numberOfWords then
         incr(numberOfWords[symbol]);
       else
         numberOfWords @:= [symbol] 1;
       end if;
     end while;
     for symbol range sort(keys(numberOfWords)) do
       writeln(symbol rpad 20 <& " " <& numberOfWords[symbol]);
     end for;
   end func;

The hash 'numberOfWords' is used to count the words (=symbols). Symbols are read from the standard input 'IN' with 'getSymbol(IN)'. Every 'symbol' is checked with the 'in' operator for presence in 'numberOfWords'. The '@:=' statement inserts the value '1' to 'numberOfWords' with the key 'symbol'. The 'keys' function delivers an unordered array of keys from 'numberOfWords'. The resulting array string is sorted with the 'sort' function.


 previous   up   next