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

Python收费账户验证项目第4部分开发技术求助

Hey there! Let's work through this fourth section of your account validation project. I'll walk you through the solution step by step, with code that hits all your requirements:

Core Requirements Recap

First, let's make sure we're aligned on what needs to be done:

  • Read account numbers (along with associated names and student IDs) from possible_valid numbers.txt
  • Use a sequential search to check each number against the valid numbers stored in valid_numbers.txt
  • Output neatly aligned results (including name, student ID, and validation status) to results.txt
Complete Solution Code

Here's the revised and expanded code that fulfills all these goals:

def main():
    # Step 1: Load valid numbers into an array (using with for safe file handling)
    valid_numbers = []
    with open('valid_numbers.txt', 'r') as f:
        for line in f:
            stripped_line = line.strip()
            if stripped_line:  # Skip empty lines
                valid_numbers.append(int(stripped_line))

    # Step 2: Read and process possible valid entries with name/student ID
    results = []
    # Add header for the output file
    results.append(f"{'姓名':<10} {'学号':<10} {'账户号码':<12} {'验证结果'}")
    results.append('-' * 45)  # Separator line

    with open('possible_valid numbers.txt', 'r') as f:
        for line_num, line in enumerate(f, 1):
            line = line.strip()
            if not line:
                continue  # Skip empty lines

            # Assume each line follows format: [Name] [Student ID] [Account Number]
            # Adjust split logic if your file uses commas/tabs instead of spaces
            parts = line.split()
            if len(parts) != 3:
                results.append(f"第{line_num}行格式错误: {line}")
                continue

            name, student_id, account_str = parts
            try:
                account_number = int(account_str)
            except ValueError:
                results.append(f"第{line_num}行无效: {line} (账户号不是有效数字)")
                continue

            # Step 3: Perform sequential search to validate the number
            is_valid = False
            for num in valid_numbers:
                if num == account_number:
                    is_valid = True
                    break

            # Step 4: Format aligned result line
            status = '有效' if is_valid else '无效'
            result_line = f"{name:<10} {student_id:<10} {account_number:<12} {status}"
            results.append(result_line)

    # Step 5: Write results to output file
    with open('results.txt', 'w', encoding='utf-8') as f:
        f.write('\n'.join(results) + '\n')

    print("校验完成!结果已保存至 results.txt")

if __name__ == "__main__":
    main()
Key Details Explained

Let's break down the important parts of this code:

  • Safe File Handling: All file operations use with statements, which automatically close files after use (no more manual close() calls that can fail).
  • Sequential Search Implementation: We loop through the valid_numbers array one by one to check for a match—this is exactly the sequential search algorithm your project requires.
  • Neat Alignment: We use Python's formatted string syntax (f"{variable:<width}") to left-align each column to a fixed width, ensuring the output is clean and easy to read.
  • Error Resilience: The code skips empty lines, catches invalid number formats, and flags malformed lines so your program doesn't crash unexpectedly.
  • Clear Output: We add a header and separator line to results.txt to make the validation results more readable.
Quick Notes for Adjustments

If your possible_valid numbers.txt uses a different separator (like commas or tabs) instead of spaces:

  • Replace parts = line.split() with parts = line.split(',') (for commas) or parts = line.split('\t') (for tabs) to match your file's format.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:17:02