2012-01-22 35 views
3

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

下面是代码:(与问题出在哪里评论)

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() 

感谢

编辑:我想保留所有存在于原始文件的空间,即使在线路是我修改了。

回答

4

您可以使用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的结尾。

+0

我试过,但它消除左边的,我不希望更改线路的所有空间。我也想保留原来的空格后,我已经改变了线。谢谢 – mikeP

+1

@mikeP:然后,您可以将其存储在其他变量中,而不是替换该行,并检查该行。我会编辑答案。 –

+0

我尝试了修改,但是我更改的行上的缩进仍然消失。即使在我更改的行中,我也想保留原始缩进。谢谢。 – mikeP

0

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

2

我认为你正在寻找一个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作品。

+0

谢谢Rik。写入的文件仍然会删除原始缩进。我发现了一种围绕@Rob Wouters解决方案的方法。 – mikeP

+0

@mikeP:'m.group(1)'包含所有缩进,所以我看不出为什么它不起作用。 –

0

使用正则表达式匹配,而不是字符串匹配:

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