如何为文本文件中匹配正则表达式的字符串实例自动编号?
嘿,我来帮你搞定给文本里匹配正则的单词加编号这个需求,给你准备了两种实用的方案,都能轻松实现你的目标:
方案1:用Python脚本实现(灵活通用)
Python的正则处理能力很强,而且脚本容易自定义调整,步骤如下:
- 写个简单的脚本:新建一个名为
add_numbering.py的文件,把下面的代码复制进去:
import re # 你的文件路径和目标正则表达式 file_path = r"C:\text\sample.txt" target_pattern = r'\bh.+y\b' # 初始化编号计数器 match_counter = 1 # 定义替换逻辑:每次匹配到就给单词加上当前编号,然后计数器+1 def add_number_to_match(match_obj): global match_counter numbered_str = f"{match_counter}>{match_obj.group()}" match_counter += 1 return numbered_str # 读取原文件内容 with open(file_path, 'r', encoding='utf-8') as original_file: text_content = original_file.read() # 执行正则替换 updated_content = re.sub(target_pattern, add_number_to_match, text_content) # 把结果写回文件(如果怕误改原文件,可以把下面的file_path改成新路径,比如r"C:\text\sample_numbered.txt") with open(file_path, 'w', encoding='utf-8') as updated_file: updated_file.write(updated_content) print("搞定!编号已经添加完成啦~")
- 运行脚本:确保你装了Python 3.x版本,打开命令提示符,进入脚本所在的文件夹,执行:
python add_numbering.py
小提醒:第一次运行建议先写入新文件,确认效果没问题再覆盖原文件哦。
方案2:用PowerShell(Windows系统自带,不用额外装软件)
如果你不想折腾Python,Windows自带的PowerShell也能搞定,直接用下面的代码:
# 设置文件路径和正则表达式 $filePath = "C:\text\sample.txt" $targetPattern = '\bh.+y\b' # 读取文件内容 $textContent = Get-Content -Path $filePath -Raw -Encoding utf8 # 初始化计数器 $matchCounter = 1 # 执行替换并添加编号 $updatedContent = [regex]::Replace($textContent, $targetPattern, { param($match) global:$matchCounter $result = "$matchCounter>$($match.Value)" $matchCounter++ return $result }) # 写入结果到文件(同样可以改成新路径避免覆盖原文件) Set-Content -Path $filePath -Value $updatedContent -Encoding utf8 Write-Host "编号添加完成!"
运行方式:打开PowerShell窗口,把上面的代码粘贴进去回车就行。
效果示例
拿你给出的原文本:
"When a happy new history ... Are you happy ... How history ... very happy ..."
处理后会变成:
"When a 1>happy new 2>history ... Are you 3>happy ... How 4>history ... very 5>happy ..."
完全符合你想要的编号效果~
内容的提问来源于stack exchange,提问作者Neal
相关产品推荐
相关产品推荐

