如何实现逐行增量替换文本并每行重置计数?替换[2s]为指定标签
我来帮你搞定这个逐行重置计数的替换难题!你之前试过的列替换、普通增量替换都没达到预期,核心问题是没实现每行独立从1开始计数——用Notepad++的Python Script插件就能完美解决,具体操作看下面:
步骤1:安装Python Script插件
- 打开Notepad++,点击顶部菜单的「插件」→「插件管理」
- 在弹出的窗口搜索「Python Script」,点击安装,完成后重启Notepad++
步骤2:创建自定义替换脚本
- 点击「插件」→「Python Script」→「New Script」,给脚本起个好记的名字(比如
LineResetIncrementReplace.py) - 把下面的代码粘贴到脚本编辑器里:
editor.beginUndoAction() total_lines = editor.getLineCount() # 遍历每一行文本 for line_num in range(total_lines): original_line = editor.getLine(line_num) new_line = "" current_count = 1 current_pos = 0 # 逐次查找当前行内的[2s]并替换 while True: match_start = original_line.find("[2s]", current_pos) if match_start == -1: # 把剩余的文本追加进去 new_line += original_line[current_pos:] break # 拼接匹配前的文本 + 替换后的内容 new_line += original_line[current_pos:match_start] + '<br /><b class="num">' + str(current_count) + '</b>' # 移动指针到当前匹配的末尾,继续查找下一个 current_pos = match_start + 4 # [2s]的长度是4 current_count += 1 # 替换原行(去掉原行的换行符,避免重复添加) editor.replaceLine(line_num, new_line.rstrip('\r\n')) editor.endUndoAction()
- 保存脚本后,回到你要处理的文本文件,点击「插件」→「Python Script」→「Scripts」→选择你刚才创建的脚本运行即可。
效果验证
用你提供的测试文本验证:
原文本:
test text various [2s] tes text various [2s] tes text various [2s]
to replace w abc-mine1.txt , [2s] to replace w abc-mine1.txt , [2s] to replace w abc-mine1.txt , [2s]
to replace w test text various [2s] tes text various [2s] tes text various [2s]
test text various [2s]
运行脚本后会得到完全符合你预期的结果:
转换后:
test text various
1 tes text various
2 tes text various
3
to replace w abc-mine1.txt ,
1 to replace w abc-mine1.txt ,
2 to replace w abc-mine1.txt ,
3
to replace w test text various
1 tes text various
2 tes text various
3
test text various
1
代码小说明
- 脚本会逐行处理文本,每一行的计数都会从1重新开始,完美解决你要的每行重置需求
- 用
editor.beginUndoAction()和editor.endUndoAction()包裹操作,要是替换错了直接按Ctrl+Z就能撤销,很方便 - 代码里的
match_start + 4是因为[2s]刚好是4个字符,确保指针跳到匹配内容的末尾,不会重复匹配
内容的提问来源于stack exchange,提问作者greektranslator

