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

如何读取外部文件统计task_manager中各用户的任务分配数量?

问题:统计每位用户被分配的任务总数

我正在生成user_overview.txt报告,已经搞定task_manager.py里注册用户总数、追踪总任务数的统计,现在卡在上统计每位用户被分配的任务总数这一步。

给定的文件格式:

  • user.txt:每行是用户名,密码
  • task.txt:每行是用户名,任务名,...

我试着用嵌套循环关联用户列表和任务文件,但统计逻辑完全不对,原代码如下:

#this part creates the user list
user_list=[]
user_dict={}
user_task=0
with open("user.txt", "r+") as user_file:
    for line in user_file.readlines():
        line= line.strip().replace(",","").split(" ")
        user_list.append(line[0])
    print(user_list)

#This part is meant to count the occurances, but not counting as I wish
with open("task.txt", "r", encoding= "utf-8-sig") as task_list:
    task_list= task_list.readlines()
    for lines in task_list:
        for x in user_list:
            if x in user_dict:
                user_dict[x]+=1
            else:
                user_dict.update({x:0})
    print(user_dict)

问题出在哪

原代码的统计逻辑完全错了:

  • 遍历任务文件每一行时,根本没提取当前任务对应的用户名,反而直接给所有用户的计数加1,等于每个任务行都会让所有用户的任务数+1,完全不是要的结果
  • 字典初始化的逻辑也乱,应该先把所有用户的计数设为0,再逐个处理任务行累加对应用户的数量

修正后的代码

# 读取用户列表并初始化任务计数字典
user_dict = {}
with open("user.txt", "r+") as user_file:
    for line in user_file.readlines():
        # 按逗号分割,取第一个元素作为用户名
        username = line.strip().split(",")[0]
        user_dict[username] = 0  # 初始任务数设为0
    print("用户列表:", list(user_dict.keys()))

# 统计每位用户的任务数量
with open("task.txt", "r", encoding="utf-8-sig") as task_file:
    for line in task_file.readlines():
        line = line.strip()
        if not line:
            continue  # 跳过空行,避免报错
        # 提取当前任务对应的用户名
        task_username = line.split(",")[0]
        # 如果该用户在字典中,任务数加1
        if task_username in user_dict:
            user_dict[task_username] += 1

print("用户任务统计结果:", user_dict)

关键修正点

  1. 读取user.txt时直接构建计数字典,每个用户初始任务数为0,不需要额外的user_list
  2. 处理task.txt时,每一行先提取对应的用户名,只给该用户的计数加1
  3. 增加了空行判断,避免空行导致的分割错误

内容的提问来源于stack exchange,提问作者Rene Van Zyl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:52:50