Lesson 2: Word Count

Overview

Our second project is a simple command line script that counts the words in a file, much like the Unix command wc.

We'll see some differences between writing Elixir modules and one-off scripts and we'll see how to read a file. The most difficult part of the lesson is deciding how to split the file into words. We'll get a taste of the both the joy and the terror of regular expressions in the process.


Source code for this episode


The process

  • Use IO.gets to ask user the name of a file to open
  • Use String.trim to get rid of trailing enter they press
  • Split the string into words with String.split and a regular expression
  • Filter out non words with Enum.filter
  • Count the words with Enum.count

The middle portion of the video also includes a detour showing some basics of regex and working with them in Elixir.

Elixir's mix utility is not used at all in this lesson. Neither is escript. Both are covered in a future lesson but there's some value in working with the very basics first, so that's what we did.

Challenge 2

See if you can extend the script build in this lesson so that the user can optionally count the number of lines or characters a file instead of the number of words.

Hint: The challenge in this lesson will be much easier if you look at the docs for Enum and see what Enum.each and Enum.at do.

(solution here)

Level up your Elixir skills

Request a free email course

Back to index

7 Comments

@abdulrahman, I have this in my VS Code settings.json (open it with cmd/ctrl + ,)

 "editor.formatOnSave": true,
- alchemist · 6 years ago

good lecture by the way auto formatting when save doesn't work for me i need to click Alt + Shift + F

- abdulrahman · 6 years ago

For those who are curious about Code.load_file/2 being deprecated, don't worry! It won't be removed until Elixir 2.0, which isn't even on the road map and Jose has said Elixir is "done".

Going forward, the function is renamed to Code.compile_file/2, and the usage is still the same. Note that the 2nd argument defaults to nil, which is why it can be called with just one argument as in this video.

- alchemist · 6 years ago

Nice one! thanks @alchemist

- jtoulouse · 6 years ago

Great video! To accelerate testing, you can use echo "word_count.exs" | elixir word_count.exs to not have to rewrite "word_count.exs" to the program every time.

- Zababa · 5 years ago

@zababa: I like the way you think! If you look closely at the video, you'll see that the terminal was Power Shell and not bash or similar, though. I think this would be the command:

type word_count.exs | (elixir word_count.exs)
- alchemist · 5 years ago

thank you for episodes

- Neon23 · 2 years ago