热线电话:13121318867

登录
2019-03-12 阅读量: 809
在行(字符串)中找到子字符串后打印下一行,直到满足条件

我想要:

从文件中读取行

查找具有指定文本的行(##必读)

在具有特定文本的行之后打印下一行,如果它们在行的开头包含星号(*)

如果下一行中没有更多带星号(*)(或不同行)的行,则必须停止

所以我到目前为止所做的是读取文件,获取行和查找特定文本,在这种情况下,它是'## Required reading'

with open(file, "r") as input:

for line in input:

if '## Required reading' in line:

print(next(input))

这将打印下一行,但这就是全部。我需要的是打印出所有下一行,如果它们在行的开头包含星号(*)。如果没有,它应该停止打印线。

我正在考虑一些条件,但我无法弄清楚如何

这是它在原始文件中的样子:

## Required reading

* [5.5. Dictionaries](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)

* [5.6. Looping Techniques](https://docs.python.org/3/tutorial/datastructures.html#looping-techniques)

* [5.7. More on Conditions](https://docs.python.org/3/tutorial/datastructures.html#more-on-conditions)

* [5.8. Comparing Sequences and Other Types](https://docs.python.org/3/tutorial/datastructures.html#comparing-sequences-and-other-types)

* [5.4. Sets](https://docs.python.org/3/tutorial/datastructures.html#sets)

* [Set Types — set, frozenset](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset)

* [7.2. Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files)

* [7.2.1. Methods of File Objects](https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects)

* [8.4. The try statement](https://docs.python.org/3/reference/compound_stmts.html#the-try-statement)

* [8.5. The with statement](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement)

* [Open](https://docs.python.org/3/library/functions.html#open)

* [file object](https://docs.python.org/3/glossary.html#term-file-object)

解决办法:试试这个:

with open(file, "r") as input:

is_required = False

for line in input:

if is_required and line.startswith("*"):

print(line)

else:

is_required = '## Required reading' in line

最后一行将is_required标志设置为True或者False取决于具有指定文本的行。

0.0000
1
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子