Python 冠军计数器程序



我在使用world_cup_champions.txt文件时遇到了一些问题。 当程序启动时,它应该读取文本文件并使用字典来存储所需的数据,使用赢得世界杯的每个国家的名称作为密钥。 我无法向用户显示"年"。下面是文本文件的示例:

Year,Country,Coach,Captain
1930,Uruguay,Alberto Suppici,José Nasazzi
1934,Italy,Vittorio Pozzo,Gianpiero Combi
1938,Italy,Vittorio Pozzo,Giuseppe Meazza
1950,Uruguay,Juan López,Obdulio Varela
1954,Germany,Sepp Herberger,Fritz Walter
1958,Brazil,Vicente Feola,Hilderaldo Bellini
1962,Brazil,Aymoré Moreira,Mauro Ramos
1966,England,Alf Ramsey,Bobby Moore

和代码:

def winners():
    f2 = open("world_cup_champions.txt","r+")
    dict_values ={}
    temp_list = []
    tmp_list1 = []
    tmp_list2 = []
    for l in f2:
        temp_list.append(l.strip())

    for val in temp_list:
        tmp_val = val.split(',')
        if tmp_val[1] not in dict_values:
            dict_values[tmp_val[1]] = 1
        else:
            dict_values[tmp_val[1]] += 1

    for key,value in dict_values.items():
        tmp_list2.append([key, value])
        tmp_list2.sort(key=lambda x: x[0])

    for val in tmp_list2:
        print(" " + val[0].ljust(14)  + " " + str(val[1]))


def main():

    print("FIFA World Cup Winners")
    print()
    print(" Country".ljust(14) + " Wins".center(9)  + "Years".rjust(14))
    print("{:15} {:5}".format("="*8, "="*5))
    winners()

if __name__ == "__main__":
    main()

这是一个CSV文件,为什么不使用CSV阅读器?

import csv
def read_data(filename):
    wins = {}
    with open(filename) as filehandle:
        reader = csv.reader(filehandle)
        next(reader)  # skip header
        for row in reader:
            year, country, coach, captain = row
            if country not in wins:
                wins[country] = []
            wins[country].append([year, coach, captain])
    return wins

这为您提供了一个很好的字典,其中包含国家/地区名称和键以及[year, coach, captain]列表作为值。

然后你可以做:

def print_winners(data):
    for country, wins in data.items():
        num_wins = len(wins)
        years = [win[0] for win in wins]
        print(country, num_wins, ', '.join(years))

这就是我解析它的方式。试图使此功能尽可能具有教育意义。如果你想深入探索它,我建议你看看Panda的文档,学习如何真正解析大而密集的CSV文件。

 def parse(path_to_file):
    from_file = open(path_to_file, "r").read()
    ret = []
    keys, splitted = from_file.split("n")[0].split(","), from_file.split("n")[1:]
    for data in splitted:
        if not data: continue
        s = data.split(",")
        print(s, keys)
        q = zip(keys, s)
        ret.append(dict(q))
    return ret
parsed_dicts = parse("path_to_your_txt")

如果你想忽略非常有用的csv模块,这里有一些变量命名得更好,可以工作,但格式不好的输出。

def winners():
    f2 = open("world_cup_champions.txt","r+")
    total_wins = {}
    years = {}
    lines = []
    country_list = []
    for line in f2:
        lines.append(line.strip())
    # Skip the first line with [1:]
    for line in lines[1:]:
        values = line.split(',')
        country = values[1]
        year = values[0]
        if country not in total_wins:
            total_wins[country] = 1
            years[country] = [year]
            country_list.append(country)
        else:
            total_wins[country] += 1
            years[country].append(year)

    for country in country_list:
        wins = total_wins[country]
        year_list = years[country]
        print(" " + country.ljust(14)),
        print(" " + str(wins)),
        print(year_list)
def main():

    print("FIFA World Cup Winners")
    print()
    print(" Country".ljust(14) + " Wins".center(9)  + "Years".rjust(14))
    print("{:15} {:5}".format("="*8, "="*5))
    winners()

if __name__ == "__main__":
    main()

这样做的方式,你把错误的信息放进了你唯一的字典。您需要不同的数据类型来保存字符串、整数和整数列表。您可以将字典的值制作成一个列表,该列表同时包含获胜总数和年份列表。

一些值得深思的东西:

import pandas as pd
def main():
    df = pd.read_csv('data.txt')
    print(df)

if __name__ == "__main__":
    main()

输出

   Year  Country            Coach             Captain
0  1930  Uruguay  Alberto Suppici        José Nasazzi
1  1934    Italy   Vittorio Pozzo     Gianpiero Combi
2  1938    Italy   Vittorio Pozzo     Giuseppe Meazza
3  1950  Uruguay       Juan López      Obdulio Varela
4  1954  Germany   Sepp Herberger        Fritz Walter
5  1958   Brazil    Vicente Feola  Hilderaldo Bellini
6  1962   Brazil   Aymoré Moreira         Mauro Ramos
7  1966  England       Alf Ramsey         Bobby Moore

您可以使用字典和列表表达式执行以下操作(以相同的方式打印教练和队长(:

def winners():
    # read file 
    with open("file.txt","r") as f:
        lines = f.readlines()
    # init dict
    dict_values = {}
    # process
    for line in lines[1:]:
        year    = line.split(",")[0]
        country = line.split(",")[1]        
        coach   = line.split(",")[2]
        captain = line.split(",")[3]     
        # fill in dict
        if not(country in dict_values.keys()):
            dict_values[country] = [[year, coach, captain]]
        else: 
            dict_values[country].append([year, coach, captain])
    # sort dict
    sorted_list = sorted(dict_values.items(),
                         key = lambda x: len(x[1]),
                         reverse = True)
    # printing
    for country, values in sorted_list:
        years    = [value[0] for value in values]
        coaches  = [value[1] for value in values]
        captains = [value[2] for value in values]
        print(" " + country.ljust(16) 
              + " " + str(len(years)).ljust(10) + " "  
              + str(years).replace('[', "").replace(']', "").replace("'", ""))

def main():
    # printing
    print("FIFA World Cup Winners")
    print()
    print(" Country".ljust(14) + " Wins".center(9)  + "Years".rjust(14))
    print("{:15} {:11} {:}".format("="*9, "="*6, "="*12))
    winners()

if __name__ == "__main__":
    main()

输出:

 Country         Wins           Years
=========       ======      ============
 Uruguay          2          1930, 1950
 Italy            2          1934, 1938
 Brazil           2          1958, 1962
 Germany          1          1954
 England          1          1966

最新更新