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

如何分离文本行并处理.txt文件中的多类成绩计算需求

Got it, let's break this down step by step—since you already know the basics of file I/O, we'll focus on the line-by-line processing logic you need. I'll use Python here because it's perfect for straightforward text manipulation tasks like this, and the code will be easy to adapt to your exact needs.

Step-by-Step Code Example

# Use a with statement to open the file—this automatically closes it when done (good practice!)
with open("your_input_file.txt", "r") as input_file:
    # Read all lines at once, strip extra whitespace/newlines, and store in a list
    lines = [line.strip() for line in input_file]

# --- Process each line individually ---
# 1. Name line: keep it as-is (we already cleaned up whitespace)
student_name = lines[0]

# 2. Quiz scores: split the string into numbers, convert to floats, calculate average
quiz_scores = list(map(float, lines[1].split()))
quiz_average = sum(quiz_scores) / len(quiz_scores)
# Optional: round to 1 decimal place for readability
# quiz_average = round(sum(quiz_scores)/len(quiz_scores), 1)

# 3. Homework scores: same logic as quizzes
homework_scores = list(map(float, lines[2].split()))
homework_average = sum(homework_scores) / len(homework_scores)

# 4. Exam scores: flexible framework since your data is incomplete
# Pick the option that matches your actual exam format:
# Option 1: Single exam score
# exam_score = float(lines[3])
# Option 2: Multiple exam scores (e.g., midterm + final)
# exam_scores = list(map(float, lines[3].split()))
# exam_average = sum(exam_scores) / len(exam_scores)
# Option 3: Weighted exam scores
# midterm, final = map(float, lines[3].split())
# exam_total = (midterm * 0.4) + (final * 0.6)

# --- Write results to a new summary file ---
with open("student_grades_summary.txt", "w") as output_file:
    output_file.write(f"Student Name: {student_name}\n")
    output_file.write(f"Quiz Average: {quiz_average:.1f}\n")  # .1f formats to 1 decimal place
    output_file.write(f"Homework Average: {homework_average:.1f}\n")
    # Add your exam result line here once you finalize the processing:
    # output_file.write(f"Exam Result: {exam_total:.1f}\n")

Key Details to Note:

  • Cleaning Lines: The list comprehension [line.strip() for line in input_file] removes annoying newline characters and extra spaces from each line, so you don't have to deal with messy raw text.
  • Splitting Scores: split() works even if there are multiple spaces between scores—no need to worry about inconsistent spacing in your input file.
  • Flexibility: The exam section has multiple commented-out options to match whatever format your full exam data ends up using. Just uncomment and adjust the code that fits your needs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:01:40