Python:对文本文件进行两次排序并拆分为不同的文件?
如何先按行长排序,然后按字母顺序排序,然后按行长拆分为单独的文件? 我有这样一个单词列表文件:Python:对文本文件进行两次排序并拆分为不同的文件?,python,sorting,split,Python,Sorting,Split,如何先按行长排序,然后按字母顺序排序,然后按行长拆分为单独的文件? 我有这样一个单词列表文件: a actors an b batter but 我需要一个文件(1.txt,2.txt)为每行长度,每个字母排序。如何做到这一点 生成的文件应如下所示: 1.txt 2.txt 等等。您可以将函数传递到sort中。类似于lambda,b:(len(a)
a
actors
an
b
batter
but
我需要一个文件(1.txt,2.txt)为每行长度,每个字母排序。如何做到这一点
生成的文件应如下所示:
1.txt
2.txt
等等。您可以将函数传递到sort中。类似于lambda,b:(len(a)
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))
files={}
对于排序中的单词(单词,lambda,b:(len(a)
您可以这样做:
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()
“每行一个文件”是什么意思?1.txt和2.txt究竟应该包含什么?n.txt应该包含每行n个字符长的input.txt,按字母顺序排序。n.B.'前面的答案“可能会随着时间的推移而改变,因为大多数用户查看的答案都是按选票计数排序的。
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))
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()
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()