2014-10-31 45 views
-1

我正在写一个新的应用程序在Python中,我需要保持行之间的缩进。如何保持行间的缩进?

我从一个文件中的代码:

line 1 
    __LINE TO CHANGE__ 
line 3 

,我想获得:

line 1 
    added code line a 
    added code line b 
line 3 

我已经尝试了一些解决方案,将\ n,\ n \ r,usign “”“”“”“字符串,字符串(”“)但我只有这两个结果:我使用replace()函数来更改一行。

感谢

编辑: 我的代码:

Reading from file and put into variable named code: 
line 1 
    __LINE TO CHANGE__ 
line 3 

text = "added code line a" 
text += "added code line b" 

available_pos = ["__LINE TO CHANGE__"] 
text_to_add = [text] 

code = code.replace(available_pos, text_to_add) 
+0

那么你的代码在哪里? – Kasramvd 2014-10-31 20:49:38

+0

你的意思是像使用反斜杠扩展一行代码? – smoothgrips 2014-10-31 20:50:06

+1

''foo“.replace(”foo“,”“+”foo“)' – 2014-10-31 20:52:50

回答

0
import re 

INDENT_RE = re.compile(r'^\s*$') 

def matching_indent(line, pattern): 
    """ 
    Returns indent if line matches pattern, else returns None. 
    """ 
    if line.endswith(pattern): 
     indent = line[:-len(pattern)] 
     if INDENT_RE.match(indent): 
      return indent 
    return None 

def replace_line(lines, pattern, replacements): 
    for line in lines: 
     indent = matching_indent(line, pattern) 
     if indent is None: 
      yield line 
     else: 
      for replacement in replacements: 
       yield indent + replacement 

您可以使用它像这样:

code = '''line 1 
    __LINE TO CHANGE__ 
line 3''' 

print('\n'.join(replace_line(
    code.split('\n'),       # one string per line 
    '__LINE TO CHANGE__',      # the string to replace 
    ["added code line a", "added code line b"] # the strings to replace with 
))) 

输出:

line 1 
    added code line a 
    added code line b 
line 3 

你也可以用一个文件中使用此,通过执行类似:

with open("input") as f: 
    print(''.join(replace_line(f, 'some pattern\n', ['foo\n', 'bar\n']))) 

请注意,在此我已添加'\n'到模式和替换的末尾。如果您打算在readlines(其中包括每行末尾的\n)的输出中使用此函数,那么您可能需要调整函数以期望它们并为您执行此操作。

+0

你的函数matching_indent和replace_line它是我正在寻找 – paganu 2014-10-31 21:38:56

0
with open("in.txt") as f: 
    lines = f.readlines() # get all lines 
    lines[1] = " added code line a\n added code line b\n" #reassign second line in lines 
    with open("in.txt","w") as f1: # overwrite the file with updated content 
     f1.writelines(lines) 

" added code line a\n added code line b\n"写上两行缩进四个空格

要更换基于特定的标准,使用枚举和如果检查:

with open("in.txt") as f: 
    lines = f.readlines() 
    for ind, line in enumerate(lines): 
     if "whatever" in line: 
      lines[ind] = " added code line a\n added code line b\n" 
    with open("in.txt","w") as f1: 
     f1.writelines(lines) 
+0

是的,但我不知道总是缩进,在哪里找到确切的线 – paganu 2014-10-31 21:07:14

+0

以及只是枚举行,如果行是一个替换,替换它使用索引然后编写 – 2014-10-31 21:08:12

+0

是的,但可以更复杂,我发布一个示例 – paganu 2014-10-31 21:09:39

0

HTML标记,3份又如改变从文件中读取template.html并投入模板变种

<div> 
    <div> 
     ___MENU___ 
    </div> 
</div> 
<div> 
    ___CONTENT___ 
</div> 
<div> 
    ___BOTTOM___ 
</div> 

接下来,我改变三个部分如下代码:

html = "<p>" 
hrml += " HELLO WORLD" 
html += "</p>" 

和等与其他两个文本取代。

available_pos = ["___MENU___", "___CONTENT___", "___BOTTOM___"] 
text_to_add = [html, html1, html2] 

模板= template.replace(available_pos,text_to_add)

0

如果你不知道什么特定的字符用来缩进(空格,制表等)或有多少是用来缩进,那么您需要从您从文件中读取的原始行中获取该行,然后将其用于行的前面。我要借&加上Padraic的回应:

with open("file.txt") as f: 
    lines = f.readlines() 
    for ind, line in enumerate(lines): 
     num_of_chars = len(line) - len(line.lstrip()) # Get the preceding characters. 
     new_line = line[:num_of_chars] + "added code line a" # Add the same to the new line. 
     lines[ind] = new_line 
相关问题