2011-02-23 55 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()