Python txt文件-读取和使用文件中的信息

COS

我有一个一般格式的txt文件:

Last Name
First Name
Year
Medal (This line only contains one number either 1,2,3 meaning gold,silver,bronze respectively)

我想做的是让用户输入一年并计算该年赢得了多少枚奖牌。然后具有另一个功能,用户可以输入名字和姓氏,该功能应打印出“约翰·史密斯(John Smith)在1864年获得了gold(1)奖牌”

def medals(medalcount):
    year= str(input("Please enter a year: "))
    with open("textfile") as f:
          medalcount+=f.read().count(year)
    return medalcount

基本上,我使用此功能来计算用户输入的字符串年份出现在txt文件中的次数。至于下一部分,我仍然对如何实际使用它感到困惑。

例子:

Smith
John
1896
1
>>> Please enter year: 1896
15 medals won in this year
检查员
def readFile(infilepath):
    answer = {}
    with open(infilepath) as infile:
        for lastname in infile:
            lastname = lastname.strip()
            firstname = infile.readline().strip()
            year = infile.readline().strip()
            medal = infile.readline().strip()

            if year not in answer:
                answer[year] = {}
            if lastname not in answer[year]:
                answer[year][lastname] = {}
            if firstname not in answer[year][lastname]:
                answer[year][lastname][firstname] = {}
            if medal not in answer[year][lastname][firstname]:
                answer[year][lastname][firstname][medal] = 0
            answer[year][lastname][firstname][medal] += 1
    return answer

def count(medalcounts):
    year = input("What year would you like to check: ").strip()
    answer = 0
    for lastname in medalcounts[year]:
        for firstname,medals in medalcounts[year][lastname].items():
            answer += sum(medals.values())
    print(answer, "medals were awarded in", year)

    firstname = input("Enter first name: ").strip()
    lastname = input("Enter last name: ").strip()
    for year,yeard in medalcounts.items():
        medals = yeard[lastname][firstname]
        for med,count in medals.items():
            print("In year", year, firstname, lastname, "won", count, '. gold silver bronze'.split()[med], "medals")

用法:

count(readFile('path/to/file'))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章