我想:
## Required reading
)的行*
,则在带有特定文本的行之后打印下一行*
)(或其他行)的行,则必须停止所以到目前为止,我所做的是读取文件,获取行并查找特定文本,在本例中为## Required reading
with open(file, "r") as input:
for line in input:
if '## Required reading' in line:
print(next(input))
这将打印出下一行,仅此而已。我需要的是,如果所有下一行在行首包含star(*),则将它们打印出来。如果没有,应该停止打印行。
我正在考虑某些while
状况,但我不知道怎么办
这是原始文件中的样子:
## 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)
但是该文件还包含其他部分,不仅包括## Required reading
部分,而且我想从此部分中仅获取带有星形(*
)的链接并打印出来。
答案 0 :(得分:4)
尝试一下:
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
,具体取决于行是否具有指定的文本。