python - 在 Python 中使用开始/结束标记搜索/替换标头
问题描述
我是 Python 新手,我有一项任务需要以特定方式清理文件中的标头,因为我的标头现在没有标准,我正在尝试提出此脚本以重用于多个实例
示例文件:
*_____________________________
* This is header text
* For details, see foobar.txt.
*_____________________________
*
*
* Code goes here
Code = x
我必须这样做的方法是定义标题的开始和结束位置,然后在添加新标题之前擦洗两者之间的所有内容(包括开始/结束点)。
目前我正在尝试使用我的
start_pos = r"*_____________________________"
end_pos = r"""*_____________________________
*
*"""
然后搜索中间的所有内容。然后我想完全连接然后删除/替换以使我的新文件如下所示:
*
* Hello, world.
*
* Code goes here
Code = x
解决方案
它来了:
\*_____________________________([\s\S]*?)\*_____________________________(?:\n\*){2}
为了匹配中间的内容,我们可以使用修改后的“点”[\s\S]
来匹配包括换行在内的所有内容。“点”匹配懒惰以避免匹配太多。
示例代码:
import re
regex = r"\*_____________________________([\s\S]*?)\*_____________________________(?:\n\*){2}"
test_str = ("*_____________________________\n"
"* This is header text\n"
"* For details, see foobar.txt.\n"
"*_____________________________\n"
"*\n"
"*\n\n"
"* Code goes here\n"
"Code = x\n")
subst = "*\\n* Hello, world.\\n*"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
推荐阅读
- javascript - 有没有办法在 ChartXY 上锁定纵横比?
- python - 如何遍历列中的每 N 行,并将值作为不带括号的列表传递 URL?
- python - 游戏的问题
- javascript - createElement() 无法处理基本路径元素
- python - 尝试计算正确的回报并使用“quad_form”设置对每种资产的最大和最小投资限制
- python - Librosa 安装 pip 失败
- swift - 如何在 SwiftUI 的 body 属性中显示函数中存在的值?
- python - spaCy 错误地将手指识别为动词
- javascript - 查询数据库时是否可以删除重复的数据字段?
- reactjs - 如何在测试中触发 useLayoutEffect?(使用 Jest 和 react-testing-library)