我有以下示例文本文件。我指定了一个我要搜索的输入值,在本例中是单词“car”,然后我想添加匹配的行“这是一辆汽车”以及它下面用两个空格缩进的所有行,一个列表。
这是文本文件的样本:
我认为它在伪代码中会看起来像这样。
def action(self, filename, input):
with open(filename, 'rb') as f:
text = f.readlines()
output = []
for lines in text:
if ("this is a" + input) in lines:
i = lines.strip()
output.append(i)
goto next line
while there is a single space
i = lines.strip()
output.append(i)
然后,如果我打印输出,我应该看到以下内容:
这是一辆车 它是红色的 它有大轮子答案 0 :(得分:0)
当您浏览for lines in text
时,请提供一个标记,说明您当前是在寻找起始文本(这是汽车)还是以下文字(以空格开头的行)。
在伪代码中:
looking_for_indents = False
for line in text:
if ("this is a " + input) in line:
print line
looking_for_indents = True
continue
if looking_for_indents:
if line.startswith(' '):
print line
else
# that's all of them, stop looking
looking_for_indents = False
附注:
input
是Python中的内置函数;命名你的论点'输入'是不好的做法readlines()
返回字符串列表,for
逐字符串迭代。 for lines in text
暗示lines
是复数,但事实并非如此。