因此,我正在开发一个项目,在该项目中,我必须对一个大型的34mb文本文件进行排序,该文件充满了歌曲数据。文本文件的每一行都有一年,唯一编号,艺术家和歌曲。我无法弄清楚的是如何有效地将数据分类到其他文本文件中。我想按艺术家名称和歌曲名称排序。可悲的是,这是我的全部:如何分类这些数据?
#Opening the file to read here
with open('tracks_per_year.txt', 'r',encoding='utf8') as in_file:
#Creating 'lists' to put information from array into
years=[]
uics=[]
artists=[]
songs=[]
#Filling up the 'lists'
for line in in_file:
year,uic,artist,song=line.split("<SEP>")
years.append(year)
uics.append(uic)
artists.append(artist)
songs.append(song)
print(year)
print(uic)
print(artist)
print(song)
#Sorting:
with open('artistsort.txt', 'w',encoding='utf8') as artist:
for x in range(1,515576):
if artists[x]==artists[x-1]:
artist.write (years[x])
artist.write(" ")
artist.write(uics[x])
artist.write(" ")
artist.write(artists[x])
artist.write(" ")
artist.write(songs[x])
artist.write("\n")
with open('Onehitwonders.txt','w',encoding='utf8') as ohw:
for x in range(1,515576):
if artists[x]!= artists[x-1]:
ohw.write (years[x])
ohw.write(" ")
ohw.write(uics[x])
ohw.write(" ")
ohw.write(artists[x])
ohw.write(" ")
ohw.write(songs[x])
ohw.write("\n")
请记住我是新手,所以请尽量把你的解释深入浅出。如果你们有其他的想法,我也很乐意听到他们的意见。谢谢!
你不应该使用'range'这一点。如果文件中的条目数量发生变化,将会破坏您的逻辑。你可以使用'为艺术家排队:'确保你总是遍历每一行。 – IanAuld
@IanAuld感谢您的建议,但我在开始时就这么做了。问题在于没有任何文件以这种方式写在artistsort.txt文件中,并且一个命中奇迹文件变得太大(〜32mb)。 – Bobbert
这与'for'循环无关。在你之前的问题中,你的逻辑存在一个问题,它阻止了任何写入该文件的内容。 for循环只是迭代你的数据,它是在它决定了你的数据实际发生了什么后。 – IanAuld