【问题标题】:How to sort file contents into list如何将文件内容排序到列表中
【发布时间】:2015-12-24 09:52:22
【问题描述】:

我需要一个解决方案来对我的文件进行如下排序:

Super:1,4,6
Superboy:2,4,9

我现在的文件是这样的:

Super:1
Super:4
Super:6

我需要帮助来跟踪每个班级成员在测验中获得的分数。有 学校三个班级,每个班级的数据需要单独保存。

我的代码如下:

className = className +(".txt")#This adds .txt to the end of the file so the user is able to create a file under the name of their chosen name.

file = open(className , 'a')   #opens the file in 'append' mode so you don't delete all the information
name = (name)
file.write(str(name + " : " )) #writes the information to the file
file.write(str(score))
file.write('\n')
file.close()    #safely closes the file to save the information

【问题讨论】:

  • 请将您的代码缩减为无法正常工作的代码段,以便于排除故障并提供帮助。

标签: python list file


【解决方案1】:

您可以使用 dict 对数据进行分组,特别是 collections.OrderedDict 以保持名称在原始文件中的显示顺序:

from collections import OrderedDict

with open("class.txt") as f:
    od = OrderedDict()
    for line in f:
        # n = name, s = score
        n,s = line.rstrip().split(":")
        # if n in dict append score to list 
        # or create key/value pairing and append
        od.setdefault(n, []).append(s)

只需将 dict 键和值写入文件即可使用 csv 模块获得所需的输出,从而为您提供漂亮的逗号分隔输出。

from collections import OrderedDict
import csv
with open("class.txt") as f, open("whatever.txt","w") as out:
    od = OrderedDict()
    for line in f:
        n,s = line.rstrip().split(":")
        od.setdefault(n, []).append(s)
    wr = csv.writer(out)
    wr.writerows([k]+v for k,v in od.items())

如果您想更新原始文件,您可以写信到tempfile.NamedTemporaryFile 并使用shutil.move 将原始文件替换为更新后的文件:

from collections import OrderedDict
import csv
from tempfile import NamedTemporaryFile
from shutil import move

with open("class.txt") as f, NamedTemporaryFile("w",dir=".",delete=False) as out:
    od = OrderedDict()
    for line in f:
        n, s = line.rstrip().split(":")
        od.setdefault(n, []).append(s)
    wr = csv.writer(out)
    wr.writerows([k]+v for k,v in od.items())
# replace original file
move(out.name,"class.txt")

如果你有多个类,只需使用循环:

classes = ["foocls","barcls","foobarcls"]

for cls in classes:
    with open("{}.txt".format(cls)) as f, NamedTemporaryFile("w",dir=".",delete=False) as out:
        od = OrderedDict()
        for line in f:
            n, s = line.rstrip().split(":")
            od.setdefault(n, []).append(s)
        wr = csv.writer(out)
        wr.writerows([k]+v for k,v in od.items())
    move(out.name,"{}.txt".format(cls))

【讨论】:

  • 你能解释一下我需要在哪里编辑我的代码吗?
  • @super123,您需要完全更改您的代码以类似于我在答案中的内容,您需要根据 dict 在我的代码中执行的操作对每个用户的分数进行分组,然后编写该密钥即名称和分数列表到一个新文件或使用shutil 方法替换原始文件。您目前在不同的行上有分数,因此首先必须按用户对它们进行分组,然后再写入
【解决方案2】:

我将提供一些伪代码来帮助您。

首先你的数据结构应该是这样的:

data = {'name': [score1, score2, score3]}

那么你应该遵循的逻辑应该是这样的:

Read the file line-by-line
    if name is already in dict:
       append score to list. example: data[name].append(score)
    if name is not in dict:
       create new dict entry. example: data[name] = [score]

Iterate over dictionary and write each line to file

【讨论】:

  • 我有一个粗略的了解,我将进行实验。谢谢
猜你喜欢
  • 1970-01-01
  • 2020-02-18
  • 2015-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多