2011-02-23 114 views
1

如何首先按行长排序,然后按字母顺序排序,然后按行长拆分为单独的文件? 我有一个单词列表文件,像这样:Python:将文本文件分类两次并分割为不同的文件?

a 

actors 

an 

b 

batter 

but 

我需要一个文件(的1.txt,2.txt)逐线的长度,每个字母顺序排序。这可以怎么做?

生成的文件应该是这样:

的1.txt

a 
b 
... 

2.txt

an 
by 
... 

+0

你说的“一个文件,每行长度”究竟是什么意思。 1.txt和2.txt包含? – Triptych 2011-02-23 00:33:18

+0

n.txt应包含n个字符长的每行input.txt,按字母顺序排序。 – Dataflashsabot 2011-02-23 00:39:39

回答

1
​​
+0

完美。非常感谢! – Dataflashsabot 2011-02-23 13:57:52

1

你可以传递函数为排序。像lambda a, b: (len(a) < len(b)) if (len(a) != len(b)) else (a < b)应该这样做。

0

添加到以前的答案:

files = {} 
for word in sort(words, lambda a,b: (len(a) < len(b)) if (len(a) != len(b)) else (a < b)): 
    if len(word) not in files:  
     files[len(word)] = open("{0}.txt".format(len(word)), "w") 
    files[len(word)].write("{0}\n".format(word))    
+0

N.B. '以前的答案'可能随时间而改变,因为大多数用户查看按票数排序的答案。 – phooji 2011-02-23 01:24:51

0

你可以这样说:

text = [x.strip() for x in """a 

actors 

an 

b 

batter 

but""".splitlines() if x.strip()] 

files = {} 
for word in text: 
    n = len(word) 
    if n not in files: 
     files[n] = open("%d.txt" % n, 'wt') 
    files[n].write(word + "\n") 

for file in files.itervalues(): 
    file.close()