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

如何使用Python删除文本文件中包含百分比的指定模式内容

问题原因

str.replace() 方法仅支持字面量字符串替换,无法识别正则规则,你写的[[0-9]+]只会匹配完全等于这个字符串的内容,自然无法识别动态的百分比括号内容,仅能删掉单独的%字符。

修正方案

使用Python内置的正则模块re的re.sub()方法完成规则匹配替换,匹配目标为:以[开头、中间包含数字/小数点、末尾带%、以]结尾的完整片段。

修改后的完整代码如下:

import re

with open('file1', 'r') as infile, open('file2', 'w') as outfile:
    content = infile.read()
    # 正则替换所有符合规则的百分比括号片段
    result = re.sub(r'\[\d+\.\d+%\]', '', content)
    outfile.write(result)

如果需要适配括号内格式有变化的场景(比如整数百分比、括号前后带空格的情况),可以用更宽松的非贪婪匹配规则:

import re

with open('file1', 'r') as infile, open('file2', 'w') as outfile:
    content = infile.read()
    # 匹配所有以[开头、%]结尾的最短片段,适配更多格式场景
    result = re.sub(r'\[.*?%\]', '', content)
    outfile.write(result)

运行上述代码即可得到你期望的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:57:02