Python如何在Markdown存储的NLP训练数据文件中搜索指定##intent行并追加新数据
纯文本检索实现方案
原代码匹配失败的核心原因
- 自定义的检索字符串和文件实际内容字符序列不一致:比如实际文件遵循Markdown标准二级标题写法,
##和intent之间有空格(即## intent:greet),但代码中拼接的标识符是##intent:greet(无空格),子串匹配自然失败。 - 读取文件时未显式指定编码:系统默认编码和md文件实际编码不匹配,读出的字符串出现乱码,无法匹配目标内容。
- 未处理行首尾的空白字符:行尾自带换行符、行首有缩进空格时,直接做整段子串匹配会因为字符序列的细微差异失败。
无需HTML转换的实现逻辑
你的md文件是自定义的结构化格式,完全不需要复杂的Markdown解析器,按行扫描做容错匹配即可,处理逻辑轻量化:
1. 按行实现容错匹配
替换原有的整文件硬匹配逻辑,对每一行先去掉首尾的所有空白字符(空格、换行、制表符),再判断核心内容是否为目标intent标题,不管标题内部有多少多余空格,都能正确识别:
def get_intent_line_index(md_file_path: str, target_intent: str) -> int: """获取目标intent标题所在的行号,未找到返回-1""" target_mark = f"intent:{target_intent}" with open(md_file_path, "r", encoding="utf-8") as f: all_lines = f.readlines() for line_num, line_content in enumerate(all_lines): stripped_line = line_content.strip() # 匹配规则:行首是Markdown二级标题,且行内包含目标intent标记 if stripped_line.startswith("##") and target_mark in stripped_line: return line_num return -1
2. 追加新的训练数据
匹配到目标行号后,直接把新的训练句子按原文件的列表格式,插入到目标行的下方即可;如果没找到对应intent,就在文件末尾新建对应的标题段落:
def append_samples_to_intent(md_file_path: str, target_intent: str, new_samples: list): line_index = get_intent_line_index(md_file_path, target_intent) # 构造需要插入的列表项内容,保持和原文件格式一致 insert_block = [f"- {sample}\n" for sample in new_samples] if line_index == -1: # 未找到对应intent,直接在文件末尾追加新段落 with open(md_file_path, "a", encoding="utf-8") as f: f.write(f"\n## intent:{target_intent}\n") f.writelines(insert_block) return # 找到目标行,重组文件内容后写回 with open(md_file_path, "r", encoding="utf-8") as f: all_lines = f.readlines() new_file_content = all_lines[:line_index+1] + insert_block + all_lines[line_index+1:] with open(md_file_path, "w", encoding="utf-8") as f: f.writelines(new_file_content)
实现注意事项
- 全程是纯文本读写操作,不需要引入Markdown转HTML的依赖,处理速度快,也不会破坏原文件的格式。
- 打开文件时必须显式指定
encoding="utf-8",避免跨平台编码不一致导致的匹配失败问题。 - 按行strip后做核心标记匹配的逻辑,对编辑器自动生成的Markdown额外格式(比如标题后的锚点、多余空格)有很好的容错性,比硬拼整行字符串的可靠性高很多。
内容的提问来源于stack exchange,提问作者adama
相关产品推荐
相关产品推荐

