Read Data From Standard Input (Task)

Now that the wordcount command can be found on the path and exits successfully, you can start implementing your first feature. In this task, you’ll add the ability to read text from the standard input (stdin) stream and display the number of lines, words, and bytes.

Acceptance Criteria

  • Your program should correctly read text from standard input and compute the count of lines, words, and bytes.
  • It should handle various newline characters properly, including those used in Linux, macOS, and Windows.
  • Trailing newlines should be taken into account for the line count.
  • Words should be defined as sequences of characters separated by whitespace.
  • If the input stream is empty, then your program should return zero for lines, words, and bytes.

Examples

Empty stream without a trailing newline:

Shell
$ echo -n | wordcount
0 0 0

Empty stream with a trailing newline:

Shell
$ echo | wordcount
1 0 1

A single word:

Shell
$ echo -n "Hello" | wordcount
0 1 5

Two words with a trailing newline:

Shell
$ echo "Hello, World!" | wordcount
1 2 14

Linux-style newline character:

Shell
$ echo -n -e "Hello\nWorld!" | wordcount
 1  2 12

macOS-style newline character:

Shell
$ echo -n -e "Hello\rWorld!" | wordcount
 0  2 12

Windows-style newline character:

Shell
$ echo -n -e "Hello\r\nWorld!" | wordcount
 1  2 13

Additional Resources

For further clarification or guidance, you can explore these resources:

If you still need more clarity, then move on to the next lesson, where you’ll find a walkthrough of a sample solution with a discussion of the suggested Python tools.

In Python, standard input (sys.stdin) behaves like a file object. Think about how you would efficiently read input from a file when the size of the data is unknown. What methods does sys.stdin provide to help with this?

What’s Next?

🕵️‍♂️ Continue to the next lesson to review the sample solution and compare your approach to solving this task.

Become a Member to join the conversation.