基于serach conditon python删除多行

2024-10-04 03:26:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用DHCP编辑器添加、删除和搜索主机。我有代码,将搜索和添加一个主机,我想我会以某种方式结合这两个删除一个主机,但没有工作。我想做的是创建元素索引f.readlines()的列表,然后使用myindex to的值,然后从我正在编辑的DHCP文件运行lines.remove(myindex)。你知道吗

示例我想搜索foonode或任何节点并删除以下格式:

    host barnode{
    option host-name "barnode";
    option root-path "0.0.0.0:/barnode";
    option subnet-mask ;
    option routers ;
    hardware ethernet  ;
    fixed-address ;
}





host foonode{
    option host-name "foonode";
    option root-path "0.0.0.0:/foonode";
    option subnet-mask ;
    option routers ;
    hardware ethernet  ;
    fixed-address ;
}




host foobarnode{
    option host-name "foobarnode";
    option root-path "0.0.0.0:/foobarnode";
    option subnet-mask ;
    option routers ;
    hardware ethernet ;
    fixed-address ;
}

我可以使用以下代码搜索文件:

def delete_host():

    host=raw_input('Please enter host you would like to delete: ');
    start = False;
    f=open(infile, 'r')
    myfile=str()
    myindex=list()
    mystr=str()
    count = 0
    lines = f.readlines()
    for line in lines:
            if re.search(host, line):
                    start = True

            if start:
                   print line
                   myindex = [lines.index(line)]   


                    if re.search('}', line):
                            break

得到这个输出:

    host foonode{

    option host-name "foonode";

    option root-path "0.0.0.0:/foonode";

    option subnet-mask ;

    option routers ;

    hardware ethernet ;

    fixed-address ;

我想在搜索条件中为f.readlines()的元素索引值创建索引列表。然后使用这些值执行lines.remove(myindex.index()),以删除运行上述代码时获得的输出。基本上我如何搜索任何节点并从文件中删除它们。 也许创建一个索引并不是解决这个问题的最佳方法,我只是在google中搜索的表达式已经用完了。你知道吗

我知道我将不得不做newfile= open('/var/tmp/foodhcp' 'w'),但我想在开始写文件之前把逻辑弄正确。你知道吗


Tags: pathnamehostlinemaskroothardwarefixed
3条回答

老实说,我不明白上面的例子。我不停地摸索,得出了以下结论:我创建了一个列表,其中填充了搜索代码的输出。然后我想写每一行不等于我的索引。我很困惑

import re
infile='C:\dhcp.txt'
def delete_host():
    infile = 'C:\dhcp.txt'
    host=raw_input('Please enter host you would like to delete: ');
    start = False;
    f=open(infile, 'r')
    nf=open(r'C:\test.txt', 'w')
    myindex=list()
    mystr=str()
    count = 0
    lines = f.readlines()

    for i, line in enumerate(lines):
            if re.search(host, line):
                start = True
                if start:
                 myindex.append(line)
                if re.search('}',line):
                    break
    for myindex in lines:
        if lines != myindex:
            mystr.join(lines)
            nf.write(mystr)
            nf.close
delete_host();

我还尝试创建一个元素列表,然后尝试使用del删除这些元素,但我一直遇到一个错误

def delete_host():
    infile = 'C:\dhcp.txt'
    host=raw_input('Please enter host you would like to delete: ');
    start = False;
    f=open(infile, 'r')
    nf=open(r'C:\test.txt', 'w')
    myfile=str()
    myindex=list()
    mystr=str()
    count = 0
    lines = f.readlines()

    for i, line in enumerate(lines):
            if re.search(host, line):
                start = True

            if start:

                #print line
                #myindex=lines.index(line)

                myindex.append(lines.index(line))
                #myindex.append(line)
                if re.search('}',line):
                    break
    print myindex
    print type(myindex[0])

    del lines[myindex]

delete_host();

我得到的错误

Please enter host you would like to delete: rest
[13, 14, 15, 16, 17, 18, 19, 7]
<type 'int'>

Traceback (most recent call last):
  File "C:\delete.py", line 52, in <module>
    delete_host();
  File "C:\delete.py", line 35, in delete_host
    del lines[myindex]
TypeError: list indices must be integers, not list

但是type返回int,所以我不明白我在做什么。你知道吗

如果已经有行列表,只需从要删除的行之前和之后的零件创建一个新的更新列表:

import re

with open('data.txt') as f:
    s = f.read()

print("Before:")
print(s)

def delete_host(s):
    host = raw_input('Please enter host you would like to delete: ')

    lines = s.split('\n')
    for i, line in enumerate(lines):
        if re.match(r'\s*host\s+' + host + '\s*{', line):
            break

    for j, line in enumerate(lines[i+1:]):
        if re.match(r'\s*}', line):
            break

    j = i + j + 1

    new_lines = lines[:i] + lines[j+1:]
    return '\n'.join(new_lines)

s = delete_host(s)
print("After:")
print(s)

(请注意,检查缺少的主机名、格式不正确的主机名或带有可能干扰regexp的有趣符号的主机名时不会出错)。你知道吗

如果您确定所有的条目总是像您描述的那样(特别是,}不会在host正文的任何地方遇到),您可以将其简化为

def delete_host(s):
    host = raw_input('Please enter host you would like to delete: ')
    return re.sub(r'\s*host\s+' + host + '\s*{[^}]*}', '', s, flags=re.MULTILINE)

最安全的方法是实际解析配置文件,获取数据结构,删除条目,然后创建一个新的配置文件。你知道吗

请注意,从正在循环的列表中删除项不会按预期的方式工作。我建议

a = [1,2,3,4,5]
del a[2:4]

a==[1,2,5]

您已经能够找到起始行和结束行,所以在找到它们之后运行del。你知道吗

相关问题 更多 >