【问题标题】:Python: Sort text file twice and split to different files?Python:对文本文件进行两次排序并拆分为不同的文件?
【发布时间】:2011-02-23 00:31:44
【问题描述】:

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

a

actors

an

b

batter

but

我需要一个文件(1.txt、2.txt)用于每个行长,每个都按字母顺序排序。如何做到这一点?

生成的文件应如下所示:

1.txt

a
b
...

2.txt

an
by
...

等等

【问题讨论】:

  • “每行长度一个文件”是什么意思 1.txt 和 2.txt 究竟应该包含什么?
  • n.txt 应包含 input.txt 的每一行,长度为 n 个字符,按字母顺序排序。

标签: python sorting split


【解决方案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】:

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

    【讨论】:

      【解决方案3】:

      添加到上一个答案:

      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))             
      

      【讨论】:

      • 注: “上一个答案”可能会随着时间而改变,因为大多数用户会查看按投票数排序的答案。
      【解决方案4】:

      你可以这样做:

      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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-11
        • 1970-01-01
        • 2021-08-04
        • 1970-01-01
        • 2023-04-09
        • 2011-10-15
        • 1970-01-01
        相关资源
        最近更新 更多