word_freq.jl in Julia
A word-frequency table from split, a Dict tally, and one sort key.
# Count word frequencies in a passage and chart the leaders.
using Printf
passage = "the rain in maine falls mainly on the plain and " *
"the rain stays on the plain"
# Tally every word; get with a default covers first sightings.
counts = Dict{String,Int}()
for word in split(passage)
counts[word] = get(counts, word, 0) + 1
end
# Rank the entries, biggest first, ties broken by the word itself.
ranked = sort(collect(counts), by = p -> (-p.second, p.first))
println(length(ranked), " distinct words")
println("word ct bar")
for (word, n) in ranked
@printf("%-7s %2d %s\n", word, n, "#"^n)
end
How it works
splitbreaks the passage;get(counts, word, 0) + 1tallies.- Sorting by
(-p.second, p.first)ranks with alphabetical ties. "#"^ndraws each word's bar under @printf columns.
Keywords and builtins used here
DictIntStringendforinusing
The run, in numbers
- Lines
- 21
- Characters to type
- 601
- Tokens
- 116
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 107 seconds.
Step 1 of 3 in Encore, step 25 of 27 in Language basics.