Julia Project: Word Counter
A word counter program counts the words in a text and how often each word appears. This project combines strings, a dictionary, a function, sorting, and files.
Count words and characters
split breaks the text on spaces and length counts the pieces. length on the text counts characters.
text = "the sun rises and the sun sets"
println(length(split(text)))
println(length(text))Count word frequencies in a function
The counting loop lives inside a function. Its local dictionary is updated safely on each word.
function countwords(text)
counts = Dict{String, Int}()
for word in split(text)
counts[word] = get(counts, word, 0) + 1
end
return counts
end
counts = countwords("the sun rises and the sun sets")
for (word, n) in sort(collect(counts))
println(word, ": ", n)
endSave a summary and read it back
The write call saves a fixed summary first. The read call then prints exactly what was saved.
write("word-summary.txt", "Words: 7")
println(read("word-summary.txt", String))Example
function countwords(text)
counts = Dict{String, Int}()
for word in split(text)
counts[word] = get(counts, word, 0) + 1
end
return counts
end
text = "the sun rises and the sun sets"
counts = countwords(text)
for (word, n) in sort(collect(counts))
println(word, ": ", n)
end
summary = "Words: $(length(split(text)))\nLetters: $(length(text))"
write("word-summary.txt", summary)
println(read("word-summary.txt", String))Key points
- Use length(split(text)) to count the words in a text.
- Use length on the text itself to count its characters.
- Count word frequencies in a dictionary with get for a default of 0.
- Wrap a counting loop in a function so its local counter is safe to update.
- Sort collect on the frequency dictionary to print words in alphabetical order.
- Write a summary to a file and read it back to check the saved text.
In this example, countwords builds a dictionary of word frequencies for the fixed paragraph. The sorted loop prints each word with its count in alphabetical order. The program then builds a summary, writes it to a file, and reads it back for the final two lines.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
Why is the counting loop wrapped in a function?