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

使用列表推导式与字典时未输出预期内容反而返回空行问题

日程变更格式化代码空行问题修复

问题根源

你的代码返回空行主要有3个核心问题:

  • 错误的嵌套循环:for line in data_lines for i in range(8) 会让每一行重复处理8次,其中大部分循环会触发else "\n"输出空行,完全打乱了时段与变更内容的对应关系
  • 操作类型匹配失效:line.split(" ")[0] 无法正确匹配希伯来语的操作关键词(比如行首可能有空格,或者希伯来语的分词逻辑和英文不同)
  • 时段i完全乱配:硬循环0-7,没有从每行数据里提取真实对应的时段编号

修正后的代码

# 读取原始文本数据
raw_data = changes_txt.text

# 操作映射字典,调整关键词匹配逻辑
operation_map = {
    'ביטול שעור': lambda line, period: f'第{period}节课取消!\n',
    'הזזת שיעור': lambda line, period: f'"{line.split(", ")[2]}"课程调整到第{period}节课\n',
    'מילוי מקום': lambda line, period: f'第{period}节课替换为"{line.split(", ")[4]}"课程\n',
    'החלפת חדר': lambda line, period: f'"{line.split(", ")[2]}"课程更换教室为{line.split(":")[-1].strip()}\n',
}

results = []
for line in raw_data.splitlines():
    line = line.strip()
    if not line:
        continue  # 跳过空行
    # 匹配操作类型(遍历字典键,检查行是否包含该关键词)
    matched_op = None
    for op_key in operation_map:
        if op_key in line:
            matched_op = op_key
            break
    if not matched_op:
        continue  # 跳过无法识别的行
    # 提取时段编号(用正则从行中提取数字,适配希伯来语文本格式)
    import re
    period_match = re.search(r'\d+', line)
    if not period_match:
        continue
    period = period_match.group()
    # 生成格式化内容
    results.append(operation_map[matched_op](line, period))

output = ''.join(results)
return output

关键修正点说明

  • 去掉了错误的嵌套循环,改为逐行处理,只处理有效内容行
  • 改用关键词包含匹配替代split(" ")[0],解决希伯来语分词的适配问题
  • 通过正则从每行提取真实的时段编号,不再硬循环无意义的0-7范围
  • 增加了空行和无效行的过滤逻辑,避免生成多余空行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:55:18