如何在给定输入值的情况下匹配文本并添加缩进行

时间:2014-03-17 03:01:20

标签: python-2.7

我有以下示例文本文件。我指定了一个我要搜索的输入值,在本例中是单词“car”,然后我想添加匹配的行“这是一辆汽车”以及它下面用两个空格缩进的所有行,一个列表。

  1. 如何搜索文本(“这是一个”+我的输入值)
  2. 如何在列表匹配后只添加缩进行?
  3. 这是文本文件的样本:

    这是一辆车  它是红色的  它有大轮子
     手动变速器

    这是一只狗  它是棕色的  和长毛皮


    我认为它在伪代码中会看起来像这样。

    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)
    

    然后,如果我打印输出,我应该看到以下内容:

    这是一辆车  它是红色的  它有大轮子
     手动变速器

1 个答案:

答案 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中的内置函数;命名你的论点'输入'是不好的做法
  • lines.strip()摆脱了开始/结束空间,如果你正在寻找它们就无济于事
  • readlines()返回字符串列表,for逐字符串迭代。 for lines in text暗示lines是复数,但事实并非如此。