Problem 6.3

Line with Most Words

Write a program line_with_most_words.py that takes a filename as command-line argument and prints the line with the most number of words from the file.

$ cat files/words.txt
one
one two
one two three
one two three four
one two three four five
two three four five
three four five
four five
five
one-two-three-four-five-six-seven

$ python line_with_most_words.py files/words.txt
one two three four five

Solution

import sys
filename = sys.argv[1]
lines = open(filename).readlines()

def word_count(line):
    return len(line.split())

longest = max(lines, key=word_count)
print(longest.strip("\n"))