【发布时间】:2019-10-26 03:08:04
【问题描述】:
我有大约 13,000 个文件需要从中删除面包屑。每个文件开头的模式大致如下:
Title
=====
| |image0| `link <link1.html>`__ |image1| ::
`link2 <link2.html>`__ ::
`link3 <link3.html>`__
| **Introduced** : VersionXXX
然而,在某些文件中,标题行和最后一行之间的部分是 2 或 4,具体取决于树的深度。无论标题行和此处显示的最后一行之间的行如何,我都希望将中间部分完全删除。我不太清楚如何做到这一点,希望能得到一些帮助。我正在使用 pycharm,他们有一个正则表达式工具(我还没有成功),但我同样很高兴使用 sed 或 python 等替代方法来遍历文件。
预期结果:
Title
=====
| **Introduced** : VersionXXX
感谢所有出色的解决方案。 最终解决方案以避免写入单独的文件:
import os
src_dir = '/PycharmProjects/docs/testfiles'
logf = open('failed_file_log.txt', 'w')
for filename in os.listdir(src_dir):
print(filename)
with open('{}/{}'.format(src_dir, filename), 'r') as f:
lines = f.readlines()
with open('{}/{}'.format(src_dir, filename), 'w') as f:
try:
for i in range(3):
f.write(lines[i])
copy = False
for line in lines:
if copy:
f.write(line)
elif line.startswith('| **Introduced**'):
copy = True
f.write(line)
except Exception as e:
logf.write('Failed to rewrite {}'.format(filename))
finally:
pass
【问题讨论】:
-
你能分享你对上述文件的预期输出吗
-
完成。谢谢。
-
标题是否总是用至少 3 个
=下划线,并且您要保存的第一行是否总是以| **Introduced**开头? -
第 2 行总是有与第 1 行中的字符相等数量的 =。是的,最后一行总是以这种方式开始。 (此模式的最后一行,顺便说一句,不在整个文件中。)
-
@Jason。明白了。
标签: python regex sed pycharm restructuredtext