如何按字母顺序将一个大文件拆分成更小的文件?

2024-10-03 19:19:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个1GB的文件充满了艺术家的名字和他们的歌曲由制表符分隔。在

Artist1    Song1    Song2    Song3 ...
Artist2    Song1    Song2    Song3 ...

我想把大文件按字母顺序分成26个不同的小文件。在

例如,我想要所有以A开头的艺术家在一个名为artists_A.txt的文件中,所有以B开头的艺术家在一个名为artists_B.txt的文件中等等

我知道sort和split命令,但是有没有一种方法可以在某些情况下利用split命令来进行拆分呢?另外,如果有更简单的方法,我也不想把每一行都单独读出来,放在正确的文件中。在

另外,好奇在Python中是否有这样的方法。在

编辑:我认为csplit可能是我问题的答案。在

编辑:AWK是使用空格分隔数据时要使用的程序!:)


Tags: 文件方法命令txt编辑名字歌曲制表符
3条回答

如果您试图在macosx版本的awk上执行此操作,可能会遇到错误。(我做到了!)在

试试这个吧,虽然没那么花哨,但很管用:

awk '{x = toupper(substr($1,1,1)); filename = "artists_" x ".txt"; print >>filename; close filename}' < songs.txt

^{pr2}$

bit可以防止“打开的文件太多”错误。在

I know about the sort and split commands, but is there a way to lever the split command to split under certain conditions?

是,split()接受可选的分隔符参数。例如,split(",")以逗号分隔。还有一个splitlines(),它处理跨平台拆分行的混乱情况。在

Also, I'd rather not read in each line individually and put it in the correct file if there's an easier way.

我总是建议不要在任何代码中打开多个file对象。这是一个灾难的药方。在

Also, curious if there's a way to do this in Python.

试试这个。在

# Read input file
with open("artists.txt") as in_file:
    artists = in_file.read().splitlines()

# Make the data structure you want
artists_sorted = {letter: [] for letter in "abcdefghijklmnopqrstuvwxyz"}
for artist in artists:
    artists_sorted[artist[0].lower()].append(artist)

# Write output files
for letter, value in artists_sorted.iteritems():
    with open("artists_%s.txt" % letter.upper(), "w") as out_file:
        out_file.write("\n".join(value))
awk '{ print >> "artists_"toupper(substr($1, 1, 1))".txt" }' < songs.txt

相关问题 更多 >