typestar

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

  1. split breaks the passage; get(counts, word, 0) + 1 tallies.
  2. Sorting by (-p.second, p.first) ranks with alphabetical ties.
  3. "#"^n draws each word's bar under @printf columns.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Encore, step 25 of 27 in Language basics.

← Previous Next →