简体   繁体   English

如何按字数对文件中的行进行排序?

[英]How to sort lines in file by number of words?

I've started a python course for beginners.我已经为初学者开设了 python 课程。 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)))

You're trying to read from file_out and write to file_in.您正在尝试从 file_out 读取并写入 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM