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

Python按姓氏搜索文本文件内容:代码输出异常问题修复

问题:按姓氏搜索捐赠数据并修正代码问题

需求说明

  • 使用Python读取sponsors.txt中的姓名与捐赠数据,按输入的姓氏搜索并输出匹配结果。

数据文件内容 (sponsors.txt)

John Smith,230.5
Sally Jones,380
Mary Smith,104.55
David McDougal,165.7
Sally Matthews,184.5
Peter Evans,300.25

预期输出

Please enter a search string: Smith
Search returned 2 results:
John Smith,230.5
Mary Smith,104.55

现有代码问题

提供的代码会重复打印全部文件内容,不符合预期:

def read_sponsor_data(file_path, word):
    with open(file_path, 'r') as file:
        content = file.read()
        name_count = content.count(list_sponsor)
        if word in content:
            print('Search returned', name_count, 'results:')
        else:
            print('Search returned no results.')
        for i in range(0, name_count):
            print(content)
    file.close()


if search_sponsor == 1:
    list_sponsor = input("Please enter a search string: ")
    read_sponsor_data("sponsors.txt", list_sponsor)
else:
    print("Invalid Input")

问题排查

  • 变量作用域混乱:函数内误用外部的list_sponsor变量,而非传入的word参数,逻辑错位。
  • 计数逻辑错误:content.count(word)统计的是字符串出现次数,无法对应真实匹配的行数,还可能误判非姓氏的匹配。
  • 打印逻辑错误:循环打印整个文件内容,而非筛选后的匹配行。
  • 多余操作:with open上下文管理器会自动关闭文件,无需手动调用file.close()。
  • 未定义变量:search_sponsor未初始化,直接判断会触发报错。

修正后的代码

def read_sponsor_data(file_path, search_surname):
    matched_lines = []
    with open(file_path, 'r') as file:
        # 逐行读取并筛选匹配姓氏的行
        for line in file:
            line = line.strip()
            if not line:
                continue
            # 拆分姓名与捐赠金额,提取姓氏部分判断
            full_name = line.split(',')[0]
            surname = full_name.split()[-1]
            if surname == search_surname:
                matched_lines.append(line)
    
    # 输出结果
    if matched_lines:
        print(f'Search returned {len(matched_lines)} results:')
        for line in matched_lines:
            print(line)
    else:
        print('Search returned no results.')

# 初始化变量并执行逻辑
search_sponsor = 1  # 可根据实际需求调整输入判断逻辑
if search_sponsor == 1:
    search_surname = input("Please enter a search string: ")
    read_sponsor_data("sponsors.txt", search_surname)
else:
    print("Invalid Input")

代码说明

  • 逐行读取文件,避免一次性加载全部内容,内存占用更低。
  • 精准拆分姓氏部分,确保仅匹配目标姓氏,避免误判名字中包含的字符串。
  • 收集所有匹配行后统一输出,彻底解决重复打印全文的问题。
  • 修复了变量作用域、未定义变量等基础错误,逻辑更清晰严谨。

内容的提问来源于stack exchange,提问作者Jack Janmejay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:20:07