python-3.x - 在python中提取文件的两行之间的一行
解决方案
如果您在迭代时无法检查上一行和下一行,您可以跟踪何时看到虚线。当看到第一条虚线时,您开始追加文本,当遇到下一条虚线时,您停止追加,例如
headings = []
start = 0
with open('/home/usr3/test1.txt') as f:
for ln in f:
# append to heading list
if start == 1:
# when the second dashed line is seen, stop appending
if ln.startswith('---'):
start = 0
continue
headings.append(ln.rstrip())
# first dashed line, indicate to start appending
if ln.startswith('---'):
start = 1
对于文本:
------------
h1
-------------
qww
qwe
qw
eqwe
-------------
h2
-------------
qwqw
ee
e
e
e
-------------
h3
-------------
输出是:
['h1', 'h2', 'h3']
推荐阅读
- npm - NestJs - CLI 插件 - 为 npm 依赖项启用 Swagger 插件
- class - Dreamweaver,类在自己的文件中查找另一个类
- gatsby - C:\Users\User\Desktop\gatsby-tutorial\.cache\json\_404_.json:JSON 中位置 0 的意外标记
- sql - 从 PostgreSQL 中的时间戳中减去 current_time
- algorithm - 估计多个节点上的运行相关性
- python - 如何获得给定数量的图层变体的独特组合,同时使用 Python 保持每个图层变体的给定比例?
- javascript - 如何在呈现页面时首先禁用按钮,然后在按下 2 个按钮时启用它
- kubernetes-helm - Skaffold 不接受 yaml 中的“命令”参数
- c - 为什么 setjmp/longjmp
- node.js - 是否安装了当前版本的 NPM (7.19.1) 的 LTS Node (v14.17.3) docker 映像?