【问题标题】:How to search and replace a text that has spaces before the text?如何搜索和替换文本前有空格的文本?
【发布时间】:2012-02-16 04:18:36
【问题描述】:

我有一个代码可以搜索一行是否以指定的单词开头,如果是,它会使用指定的输入更改整行。但是,如果行由空格缩进,它对某些行不起作用?有没有办法直接阅读文本并忽略空格。

这是代码:(用 cmets 说明问题所在)

import os

def template(filein):
    currdir = os.getcwd() # get current directory
    new_file = open(os.path.join(currdir,'maindir','template.in'),'wt')
    old_file = open(filein)
    for line in old_file:
        if line.startswith('   indent'):
            # this part works well because I put the exact number of spaces present in the text before the search word
            new_file.write('   indent == %s \n' % str('%(indent)s'))
        elif line.startswith('noindent'):
            # this part can't find noindent because i didn't specify the spaces before that that is present in the text
            new_file.write('noindent == %s \n' % str('%(noindent)s'))
        else:
            new_file.write(line)
    new_file.close()
    old_file.close()

谢谢

编辑:我想保留原始文件中存在的所有空格,即使在我修改的行中也是如此。

【问题讨论】:

    标签: python search replace spaces


    【解决方案1】:

    您可以使用lstrip 删除行首(左侧)的空格:

    for line in old_file:
        stripped_line = line.lstrip()
        # do your matching here against `stripped_line` instead of `line`
        # `line` still contains the original, non-stripped line
    

    在旁注中,我建议使用with open('filename') as new_file,而不是您现在正在做的事情。这将创建一个文件可用的块,并确保文件在块的末尾关闭。请参阅文档中 this section 的结尾。

    【讨论】:

    • 我试过了,但它删除了左侧所有我不想更改的行的空格。我还想在更改线路后保留原始空间。谢谢
    • @mikeP:那么,您可以将其存储在另一个变量中,而不是替换该行,并对其进行检查。我会编辑答案。
    • 我尝试了修改,但是我更改的行上的缩进仍然消失了。即使在我更改的行中,我也想保留原始缩进。谢谢。
    • @mikeP,在这种情况下,您可能想查看Rik Poggi's answer
    【解决方案2】:

    使用lstrip 函数来做到这一点。

    【讨论】:

      【解决方案3】:

      我认为您正在寻找regular expression

      import re
      
      def replace(line, test_word, new_line):
          m = re.match(r'(\s*)(.*)', line)
          if m.group(2).startswith(test_word)
              return m.group(1) + new_line
      

      例子:

      >>> lines = ['    my indented line', 'my not indented line']
      >>> for line in lines:
      ...     replace(line, 'my', 'new line')
      '    new line'
      'new line'
      

      您可以在官方文档some examples 中找到group 的工作原理。

      【讨论】:

      • 谢谢瑞克。写入的文件仍会删除原始缩进。我找到了解决@Rob Wouters 解决方案的方法。
      • @mikeP: m.group(1) 包含你所有的缩进,所以我看不出它为什么不起作用。
      【解决方案4】:

      使用正则表达式匹配代替字符串匹配:

      if re.match('^\s*indent\b', line): 
          # line starts with 0 or more whitespace followed by "indent" 
      

      【讨论】:

        猜你喜欢
        • 2013-06-13
        • 1970-01-01
        • 2015-01-09
        • 2023-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多