Python:对文本文件进行两次排序并拆分为不同的文件?

时间:2011-02-23 00:31:44

标签: python sorting split

如何按行长度排序,然后按字母顺序排序,然后按行长度分割成单独的文件? 我有一个像这样的单词列表文件:

a

actors

an

b

batter

but

我为每个行长度要求一个文件(1.txt,2.txt),每个文件按字母顺序排序。怎么可能这样做?

生成的文件应如下所示:

的1.txt

a
b
...

2.txt

an
by
...

4 个答案:

答案 0 :(得分:1)

您可以将函数传递给sort。像lambda a, b: (len(a) < len(b)) if (len(a) != len(b)) else (a < b)之类的东西应该这样做。

答案 1 :(得分:1)

from collections import defaultdict

OUTF = "{0}.txt".format

def sortWords(wordList):
    d = defaultdict(list)
    for word in wordList:
        d[len(word)].append(word)
    return d

def readWords(fname):
    with open(fname) as inf:
        return [word for word in (line.strip() for line in inf.readlines()) if word]

def writeWords(fname, wordList):
    wordList.sort()
    with open(fname, 'w') as outf:
        outf.write('\n'.join(wordList))

def main():
    for wordLen,wordList in sortWords(readWords('words.txt')).iteritems():
        writeWords(OUTF(wordLen), wordList)

if __name__=="__main__":
    main()

答案 2 :(得分: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))             

答案 3 :(得分: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()