Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 38 ยท Applications

Text Processing and Ports

Read and write files with Racket ports, process lines and words, use regexps and string functions, and run a JavaScript text-pipeline stand-in with a string port model.

Many real programs read some text, transform it and write something out: log analysis, configuration, reports, little converters. Racket treats all input and output through ports: an input port is a source you read from, and an output port is a place you write to. A file, a network connection, a string in memory and the console are all ports, so the same functions work on each.

In this lesson you will use ports for files and strings, process text line by line, use regular expressions, and see how the in-memory string port makes testing easy. It follows Testing with rackunit in spirit: code that takes ports is easy to test.

Racket cannot run here, so the Racket code is read-only, and results are shown only when certain. The runnable JavaScript blocks are stand-ins that model ports with small classes.

Output and input basics

The console is the current output port, so display, displayln, write and printf all write to it:

RACKET
(displayln "hello")                     ; hello
(write "hello")                         ; "hello" (with quotes, as code)
(printf "~a has ~a items~n" "cart" 3)   ; cart has 3 items
(format "~a-~a" 1 2)                    ; => "1-2" (returns a string)

display prints for people; write prints in a form the reader can read back. Files are opened with call-with-output-file or with-output-to-file, which close the file for you, even on errors:

RACKET
(call-with-output-file "notes.txt" #:exists 'replace
  (lambda (out)
    (fprintf out "first line~n")
    (fprintf out "second line~n")))

(call-with-input-file "notes.txt"
  (lambda (in)
    (read-line in)))      ; => "first line"

Higher-level helpers do the common jobs in one call: file->string, file->lines, display-to-file, display-lines-to-file (from racket/file).

Reading line by line

read-line returns the next line, or the special eof value at the end. in-lines turns a port into a sequence for for loops:

RACKET
(define (count-words in)
  (for/sum ([line (in-lines in)])
    (length (string-split line))))

(call-with-input-file "notes.txt" count-words)   ; => 4

Because count-words takes a port, it also works on an in-memory string:

RACKET
(count-words (open-input-string "one two\nthree four five"))  ; => 5

open-input-string and open-output-string (with get-output-string) create ports backed by strings, which is exactly what you want for unit tests: no files to create or delete.

Strings and regular expressions

Racket has a full string library (string-split, string-join, string-trim, string-replace, string-upcase) and two regexp flavors. The common one is written #rx"..."; #px"..." adds Perl-style shortcuts like \\d and \\w.

RACKET
(string-split "a,b,,c" ",")                 ; => '("a" "b" "" "c")
(string-join '("x" "y" "z") "-")            ; => "x-y-z"
(string-trim "  padded  ")                  ; => "padded"
(regexp-match #px"(\\d+)-(\\d+)" "tel 555-1234")
;; => '("555-1234" "555" "1234")
(regexp-replace* #px"\\s+" "a   b \t c" " ")  ; => "a b c"
(regexp-match? #rx"^[a-z]+$" "hello")       ; => #t

regexp-match returns the whole match followed by each group (or #f if nothing matched), regexp-match* returns all matches, and regexp-replace* replaces every match. Remember that in a Racket string literal a backslash must be doubled.

Stand-in: a text pipeline with string ports

JavaScript has no ports, so this stand-in defines tiny InputPort and OutputPort classes and a wordFrequencies function that works on any input port. It mirrors the Racket design: the function does not care where the text comes from.

JS Stand-in: string ports and a word counter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Because wordFrequencies reads from an input port and writes to an output port, it can be tested with strings and later pointed at a real file.

Stand-in: parsing simple records

A typical task: turn lines such as alice,34,paris into structured data, with validation and a clear error. The regular expression here follows the same idea as regexp-match with groups.

JS Stand-in: parsing and validating lines

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Practical tips

  • Use call-with-input-file and call-with-output-file so ports are closed even if an error occurs.
  • Check for eof ((eof-object? x)) when using read-line or read directly.
  • Specify #:exists 'replace or 'append explicitly when writing: the default is to raise an error if the file exists.
  • For binary data use read-bytes and write-bytes; strings assume UTF-8.
  • with-output-to-string captures anything printed inside its body into a string, handy for tests.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does read-line return at the end of the input?

    It returns eof, which you test with eof-object?.
  2. 2. Why take a port as a parameter rather than a file name?

    A port-based function does not care about the source, so tests can pass open-input-string.
  3. 3. What does (regexp-match #px"(\\d+)-(\\d+)" "tel 555-1234") return?

    You get '("555-1234" "555" "1234"), or #f when nothing matches.
  4. 4. What is call-with-output-file good for?

    It opens the file, calls your function with the port and always closes the port afterward.

Summary

  • Input and output go through ports: console, files, strings and network connections all look alike.
  • Use call-with-input-file/call-with-output-file for safe file handling and in-lines for line loops.
  • string-split, string-join, string-trim, regexps and regexp-replace* cover most text jobs.
  • String ports (open-input-string, with-output-to-string) make text code easy to test.
  • Write functions that accept ports, not file names.

Next: Web Servers and Servlets