Word counting 2
Jan 11, 2014 0:26:28 GMT 1
Post by Deleted on Jan 11, 2014 0:26:28 GMT 1
Sorry for bringing back this ancient topic (http://basic-converter.proboards.com/thread/240/word-counting), but this is a good example of how BaCon is getting better and better. This version requires BaCon 2.4.0:
It may be not the fastest solution*, but, because it uses regular expressions and associative arrays, it's shorter and easier to read. And finally, it produces exactly the same result like Python, Perl, Ruby and other languages.
*Associative arrays are not as fast as in some other languages.
DECLARE kawalki$[100000] TYPE STRING
DECLARE zastapione$[100000] TYPE STRING
DECLARE wszystkie ASSOC int
PRINT "Reading the file..."
OPEN "Bible.txt" FOR READING AS ksiazka
x = 0
WHILE NOT(ENDFILE(ksiazka)) DO
READLN akapit$ FROM ksiazka
kawalki$[x] = LCASE$(akapit$)
INCR x
WEND
CLOSE FILE ksiazka
PRINT "Counting..."
FOR y = 0 TO x
zastapione$[y] = REPLACE$(kawalki$[y], "[^a-z]", " ", TRUE)
NEXT
wsz = 0
uni = 0
FOR y = 0 TO x
FOR slowo$ IN zastapione$[y]
IF LEN(slowo$) > 1 OR slowo$ = "a" OR slowo$ = "i" THEN
IF ISKEY(wszystkie, slowo$) = TRUE THEN
INCR wszystkie(slowo$)
INCR wsz
ELSE
wszystkie(slowo$) = 1
INCR uni
INCR wsz
ENDIF
ENDIF
NEXT
NEXT
PRINT "All words - ", wsz
PRINT "Unique words - ", uni
PRINT "Sorting and writing to the file..."
SORT wszystkie
OPEN "words2.txt" FOR WRITING AS wynik
WRITELN "All words - " & STR$(wsz) TO wynik
WRITELN "Unique words - " & STR$(uni) TO wynik
WRITELN " " TO wynik
LOOKUP wszystkie TO klucze$ SIZE rozmiar
FOR x = rozmiar - 1 TO 0 STEP -1
WRITELN klucze$[x] & " - " & STR$(wszystkie(klucze$[x])) TO wynik
NEXT
CLOSE FILE wynik
PRINT "Done!"
It may be not the fastest solution*, but, because it uses regular expressions and associative arrays, it's shorter and easier to read. And finally, it produces exactly the same result like Python, Perl, Ruby and other languages.
*Associative arrays are not as fast as in some other languages.