How to sort lines in file by number of words?

Question:

I’ve started a python course for beginners.
I have a file with lines:

"I was angry with my friend

I told my wrath my wrath did end

I was angry with my foe

I told it not my wrath did grow"

I need to sort lines by number of words in line and inside each line, the words need to be ordered by the number of letters in them.

The result need to be saved into file

My code:

with open('input.txt', 'r') as file_in, with open('output.txt', 'w') as file_out:
    file_in.write('n'.join(sorted([' '.join([''.join(sorted(w)) 
    for w in line.split()]) for line in file_out.read().split('n')], key=len)))
Asked By: ddcrunk

||

Answers:

You’re trying to read from file_out and write to file_in.

def lines(filename):
    with open(filename) as fin:
        for line in fin:
            yield ' '.join(sorted(line.split(), key=len))

with open('output.txt', 'w') as fout:
    print(*sorted(lines('input.txt'), key=lambda x:len(x.split())), sep='n', file=fout)
Answered By: Cobra
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.