Python-2:将文本文件中的行分配给变量

时间:2016-03-03 20:21:08

标签: python python-2.7

我目前正在尝试为一个单项目的文本文件制作竞赛记分牌。

每个参赛者都有一个competitor_no,competitor_name和3个分数,它们都显示在文本文件的不同行中(因此每个参赛者的数据需要5行),例如:

1
Eliza Ianson
9.19
11.79
21.66
2
Cece Durant
17.03
7.02
17.72

我需要能够添加3个分数才能获得总分。我有50个竞争对手,需要将它们全部进行比较,以显示打印竞争对手数量,名称和总分的前3名竞争对手。有没有办法将行值赋给变量?

显然,我需要一次比较5行,以获得每个竞争对手所需的信息,并处理数据,这就是我在程序中设置代码的方式。

 file = open('veggies_2014.dat')

    for line in file:

            first_place = []
            second_place = []
            third_place = []

            a = 1 
            b = 2
            c = 3
            d = 4
            e = 5

            if line == a:
                    competitor_no = line
            elif line == b:
                    competitor_name = line
            elif line == c:
                    cucumber = line
            elif line == d:
                    carrot = line
            elif line == e:
                    runner_bean = line

            a += 5
            b += 5
            c += 5
            d += 5
            e += 5

            score = float(cucumber) + float(carrot) + float(runner_bean)
            print(score)

            if score > first:
                    first = score
                    first_place.append(competitor_no)
                    first_place.append(competitor_name)
                    first_place.append(score)
            elif score > second:
                    second = score
                    second_place.append(competitor_no)
                    second_place.append(competitor_name)
                    second_place.append(score)
            elif score > third:
                    third = score
                    third_place.append(competitor_no)
                    third_place.append(competitor_name)
                    third_place.append(score)

    file.close()

    print (first_place)
    print (second_place)
    print (third_place)  

当我正在处理包含数字的文件时,我可以获得得分if语句,但必须包含该名称是我似乎绊脚的地方。

有什么建议吗?

4 个答案:

答案 0 :(得分:0)

你可以做这样的事情(没有经过测试 - 但你明白了): 基本上,每次计数到0时,你都会将得分保存在personDict中,并将该人的姓名作为关键....

count = 0
c1_no = None;
personDict = dict()
with open("veggies_2014.dat") as f:
    score = 0
    for line in f:
        if count%5==0:
          if c1_no:
              personDict[c1_no] = score
          c1_no = line
          score = 0
       elif count%5 == 1:
          c1_name = line
       elif count%5 in (2,3,4):
           score += float(line)
       count += 1

 #now do whatever you want with the personDict..you will have something like {Emily:10} assuming Emily's scores were 2,3,5 etc

答案 1 :(得分:0)

以下是我提出的建议:

file_content = '''1
Eliza Ianson
9.19
11.79
21.66
2
Cece Durant
17.03
7.02
17.72
3
Foo Bar
10
9.5
11.2
4
Superman
7.9
12.15
9.75
'''


def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    """ from http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python """
    for i in xrange(0, len(l), n):
        yield l[i:i+n]


users = []
for user_data in chunks(file_content.splitlines(), 5):
    user_id = int(user_data[0])
    user_name = user_data[1]
    scores = list(map(float, user_data[2:]))
    overall_score = sum(scores)

    users.append(dict(
        user_id=user_id,
        user_name=user_name,
        scores=scores,
        overall_score=overall_score
    ))


top_3 = sorted(users, key=lambda x: x['overall_score'], reverse=True)[:3]

答案 2 :(得分:0)

由于您知道信息在文件中的显示顺序,因此请尝试一次以五行为单位读取文件,然后相应地处理。在下面的实现中,我将信息存储在2D列表中,然后按分数排序,从而获得最高分。

data = []
count = 1
with open("veggies_2014.dat") as f:
    line = f.readline()
    while line and int(line) == count:
        score = 0
        entry = []
        entry.append(f.readline())   #read line with c_name
        for i in range(3):
            score += float(f.readline())     #add scores
        entry.append(score)
        data.append(entry)
        line = f.readline()
        count += 1

print(data)
data = sorted(data, key = lambda l:l[1], reverse = True)
print()
print(data)

答案 3 :(得分:0)

我在一些答案的帮助下使用了完成的代码。虽然我选择在我的应用程序中将它分成不同的功能,但部分可以重复使用。

    data = []
    count = 1

    print("")
    print("For 2014 Results please enter: veggies_2014.txt ")
    print("For 2015 Results please enter: veggies_2015.txt")
    print("For 2016 Results please enter: veggies_2016.txt ")
    fname = raw_input("Enter file name:  ")
    with open(fname) as f:
            line = f.readline()
            while line and float(line) == count:
                    score = 0
                    entry = []
                    entry.append(count)
                    entry.append(f.readline().strip())          
                    for i in range(3):
                            score += float(f.readline()) #add scores
                    score = round(score, 2)
                    entry.append(score)
                    data.append(entry)
                    line = f.readline()
                    count += 1

    data = sorted(data, key = lambda l:l[2], reverse = True)
    print("")
    final=[]

    for line in data:
            for i in line:
                    final.append(i)

我添加了此代码以更清晰地显示记分板。

    a=0
    b=3
    x=1
    for i in range(0,3):
            place=[]
            place = final[a:b]
            string = " ".join(str(x) for x in place)
            print (str(x) + ". " + string)
            a += 3
            b += 3
            x += 1

    print("")