You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从数据文件读取字符串姓名与整数分数并修复类型错误

读取高尔夫球员数据的类型错误修复方案

问题背景

已实现将高尔夫球员姓名和分数写入golf.txt的代码:

def main():
    num_players = int(input("How many players are there?"))
    golf = open("golf.txt", 'w')
    for i in range(num_players):
        player_name = str(input("What is the player's name?"))
        player_score = int(input("What is their golf score?"))
        golf.write(player_name + '\n')
        golf.write(str(player_score) + '\n')
    golf.close()

main()

文件输出内容示例:

Palmer
120
Nicholas
118
Dalton
150
Woods
122
Player
124

尝试读取文件并找出最佳、最差球员时,出现**str对象无法被解释为整数**的错误,错误代码如下:

def main():
    golf = open("golf.txt",'r')
    large = 125
    small = 119
    name=golf.readline()
    while name != '':
        for i in range(name):
            name = golf.readline()
            score = int(golf.readline())
            if score > large:
                large = score
                print(name,"is the worst at golf")
    while name != '':
        for i in range(name):
            name = golf.readline()
            score = int(golf.readline())
            if score < small:
                large = score
                print(name, "is the best at golf")

main()

错误原因

  • 核心类型错误:for i in range(name)中,name是字符串类型,而range()函数要求传入整数参数,直接传入字符串会触发类型不匹配错误。
  • 逻辑缺陷:
    • 两次独立的while循环:第一次循环读完文件后,文件指针已移至末尾,第二次循环无法读取任何内容。
    • 初始值不合理:large=125和small=119是固定值,若文件中存在超出该范围的分数,会导致统计错误。
    • 未处理换行符:readline()会保留文本末尾的\n,导致姓名输出时带换行符。
    • 变量名错误:第二个循环中误将small赋值给large,逻辑完全错误。

修复后的代码

以下代码解决了所有问题,通过一次遍历完成最佳、最差球员的统计,同时使用with语句自动管理文件资源:

def main():
    # 初始化最佳/最差球员的变量
    best_score = None
    best_player = ""
    worst_score = None
    worst_player = ""

    # 使用with语句自动关闭文件,更安全
    with open("golf.txt", 'r') as golf_file:
        while True:
            # 读取姓名并去除换行符和空白字符
            player_name = golf_file.readline().strip()
            # 如果姓名为空,说明文件读完了
            if not player_name:
                break
            # 读取分数并转换为整数
            player_score = int(golf_file.readline().strip())

            # 更新最佳球员(高尔夫分数越低越好)
            if best_score is None or player_score < best_score:
                best_score = player_score
                best_player = player_name
            # 更新最差球员(分数越高越差)
            if worst_score is None or player_score > worst_score:
                worst_score = player_score
                worst_player = player_name

    # 输出结果
    print(f"{best_player} is the best at golf with a score of {best_score}")
    print(f"{worst_player} is the worst at golf with a score of {worst_score}")

main()

关键改进点

  • 移除了错误的range(name)循环,改为逐行配对读取姓名和分数。
  • 使用strip()去除读取内容的换行符和空白字符,避免字符串干扰。
  • 用None初始化分数变量,确保能正确捕获文件中的第一个分数作为初始值。
  • 一次遍历完成两种统计,避免重复读取文件。
  • 使用with语句自动管理文件,无需手动调用close(),避免资源泄漏。

内容的提问来源于stack exchange,提问作者Owen Adams-Mejia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 13:20:35