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

Apple ][(2)模拟器代码开发:行号处理与文件编辑需求

Apple ][ 模拟器代码行处理解决方案

以下是针对你需求的具体实现思路与代码示例(以Python为例,逻辑可适配其他语言):

输入解析:拆分行号与代码内容

首先要准确分离用户输入中的行号和代码:

  • 若输入仅为数字(如20):标记为删除该行的操作
  • 若输入是数字+代码(如20 x = 0):提取开头数字作为目标行号,剩余部分为待写入的代码
def parse_user_input(user_input):
    input_parts = user_input.strip().split(maxsplit=1)
    if not input_parts:
        return None, None
    if input_parts[0].isdigit():
        target_line = int(input_parts[0])
        code_content = input_parts[1].strip() if len(input_parts) > 1 else ""
        return target_line, code_content
    return None, None

核心功能实现

写入指定行且不含行号

通过将文件内容转为列表,利用行号-1=列表索引的映射关系定位目标行:

  1. 读取文件所有行到列表(自动去除换行符)
  2. 若目标行号超过当前文件行数,填充空白行至目标行位置
  3. 将列表对应索引位置的内容替换为解析出的代码(无行号)

删除指定行及后续空白行

当输入仅为行号时:

  1. 删除列表中对应索引的行
  2. 从文件末尾向前遍历,移除所有连续的空白行,仅保留有效非空内容

完整代码:

def handle_apple2_code(file_path, user_input):
    target_line, code_content = parse_user_input(user_input)
    if target_line is None:
        return  # 无效输入,直接返回
    
    # 读取现有代码行
    try:
        with open(file_path, "r") as f:
            code_lines = f.read().splitlines()
    except FileNotFoundError:
        code_lines = []
    
    target_index = target_line - 1
    
    if code_content:
        # 写入操作:确保目标行存在,替换内容
        if target_index >= len(code_lines):
            # 填充空白行到目标行
            code_lines.extend([""] * (target_index - len(code_lines) + 1))
        code_lines[target_index] = code_content
    else:
        # 删除操作:移除目标行(如果存在)
        if 0 <= target_index < len(code_lines):
            del code_lines[target_index]
        # 清理末尾多余空白行
        while code_lines and code_lines[-1].strip() == "":
            code_lines.pop()
    
    # 写回文件
    with open(file_path, "w") as f:
        f.write("\n".join(code_lines) + "\n")

场景测试

  • 输入20 x = 0:文件第20行被替换为x = 0,无行号
  • 输入20:文件第20行被删除,同时末尾所有空白行被清理,仅保留有效代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 07:22:50