【问题标题】:How can I sort this data?如何对这些数据进行排序?
【发布时间】:2014-01-29 16:28:46
【问题描述】:

所以,我正在做一个项目,我必须对一个包含歌曲数据的 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。如果文件中的条目数发生更改,它将破坏您的逻辑。您可以使用for line in artists: 确保您始终检查每一行。
  • @IanAuld 感谢您的建议,但我一开始就这样做了。问题是,artistsort.txt 文件中没有写入任何内容,并且一击奇迹文件变得太大(~32mb)。
  • 这与for 循环无关。在您之前的问题中,您的逻辑存在问题,阻止将任何内容写入文件。 for 循环只是迭代您的数据,它之后的内容决定了您的数据实际发生的情况。

标签: python sorting file-management


【解决方案1】:

请尝试以下方法:

from operator import attrgetter

class Song:
    def __init__(self, year, uic, artist, song):
        self.year = year
        self.uic = uic
        self.artist = artist
        self.song = song

songs = []

with open('tracks_per_year.txt', 'r', encoding='utf8') as in_file:
    for line in in_file:
        year, uic, artist, song = line.split("<SEP>")
        songs.append(Song(year, uic, artist, song))
        print(year)
        print(uic)
        print(artist)
        print(song)

with open('artistsort.txt', 'w', encoding='utf8') as artist:
    for song in sorted(songs, key=attrgetter('artist', 'song')):
        artist.write (song.year)
        artist.write(" ")
        artist.write(song.uic)
        artist.write(" ")
        artist.write(song.artist)
        artist.write(" ")
        artist.write(song.song)
        artist.write("\n")

【讨论】:

  • 非常感谢您的想法。我没有得到的唯一部分是“for song in sorted(songs, key=attrgetter('artist', 'song')):”。解释一下。
  • 内置python函数sorted()songs列表中返回一个新的排序列表。可选参数key 是从songs 的每个元素返回的函数键。在本例中是 attrgetter 函数,它从 Song 对象返回 artistssong 字段。
【解决方案2】:

pandas 的简洁性无与伦比。阅读您的文件:

import pandas as pd

data = pd.read_csv('tracks_per_year.txt', sep='<SEP>')
data
#    year    uic     artist      song
#0   1981    uic1    artist1     song1
#1   1934    uic2    artist2     song2
#2   2004    uic3    artist3     song3

然后按特定列排序并写入新文件即可:

data.sort(columns='year').to_csv('year_sort.txt')

【讨论】:

    【解决方案3】:

    您可以将数据导入基于字典的结构中,即针对每个艺术家和歌曲:

    data = {artist_name: {song_name: {'year': year, 'uid': uid}, 
                          ... }, 
            ...}
    

    然后当你输出时,使用sorted按字母顺序获取它们:

    for artist in sorted(data):
        for song in sorted(data[artist]):
            # use data[artist][song] to access details
    

    【讨论】:

      猜你喜欢
      • 2014-07-14
      • 1970-01-01
      • 2023-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 2013-01-03
      相关资源
      最近更新 更多