Deblank
June 28, 2019
Today’s task is easy. I expect to see lots of imaginative and over-the-top solutions:
Write a program that passes its input to its output, removing any lines that are either empty or contain only “white” characters like space and tab.
Your task is to write a program that removes blank lines from files. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Python 3:
def remove_blank_lines(file, encoding='utf8'): """Return a list of the non-blank lines in a file""" non_blanks = [] with open(file, 'r', encoding=encoding) as fobj: for line in fobj: if line.strip(): non_blanks.append(line) return non_blanksAs a pseudo-one-liner in Python, abusing list comprehension syntax:
import sys; [sys.stdout.write(line) for line in sys.stdin if line.strip()]
Rust version:
fn strip(s: &str) -> String { s.chars().filter(|&c| " \t\n\r".find(c).is_none()).collect() } fn main() { println!("{}", strip( "this is a test of the emergency broadcast system \t!")); }Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=930b30b55bac3d1783827bd1cd70f06b
gawk /\S/
There’s supposed to be two backslashes in front of the “S” in that gawk expression. Looks like the text-entry form here stripped one of them.
Here’s a solution with a vim command:
Intriguing problem, with a practical aspect to it! Here is my approach to it, using Julia:
function ContainsOnlyWhiteCharacters(text::AbstractString)
wc = [‘ ‘, ‘\t’, ‘\n’] # white characters
end
function process(fn::AbstractString)
f = open(fn)
lines = readlines(f)
close(f)
n = length(lines)
ind = BitArray(undef, n)
end
Cheers
An unimaginative, under-the-top Haskell version. The octal escapes in the printf produce a Unicode thin space.
#lang racket
(require 2htdp/image)
(let ((white (car (image->color-list (text " " 12 "black")))))
(for ([line (port->lines)])
(unless
(for/and ([pixel (image->color-list (text line 12 "black"))])
(equal? pixel white))
(displayln line))))