删除文件中包含确切字符串 (Python) 的行

Deleting a line in file containing exact string (Python)

import re
print "List of names:"
f=open('names.txt','r')  #look below
lines = f.readlines()
for line in lines:
    info = line.split('|')
    names = info[0]
    print names
name = raw_input("Enter the name of the person you want to delete: ")
f.close()

f = open('names.txt','w')
for line in lines:
    if not re.match(name,line):
        f.write(line)
        break

print "That person doesn't exist!"

names.txt :

John|22|Nice
Johnny|55|Better than John
Peter|25|The worst

因此,当您 运行 程序时,会打印姓名列表,然后您必须输入要删除其行的人的姓名。

问题是,如果我输入 John,它会删除第一行和第二行,但我只想删除第一行。我的猜测是我做的 re.match() 不对。我尝试了 re.match(name,names) 但这也不起作用。

所以,你在 name 中输入的字符串应该与 names 中的字符串进行比较,如果完全匹配,它应该删除具有 name 的行作为第一个元素。

我发现了很多类似的问题,但是我的函数包含了所有的东西,我无法弄明白。

re.match匹配字符串开头的字符串。您可以在表达式中添加单词分隔符

name + r'\b'

但在你的情况下,re 有点矫枉过正,简单比较就可以了

name == line.partition('|')[0]

顺便说一句,如果你只需要在开头或结尾拆分一次 - partitionrpartition 函数是更好的选择

编辑

时间:

    >>> timeit('line.startswith(name+"|")', 'line="John|22|Nice";name="John"')
    0.33100164101452345

    >>> timeit('line.partition("|")[0] == name', 'line="John|22|Nice";name="John"')
    0.2520693876228961

    >>> timeit('re.match(name+r"\b", line)', 'import re; line="John|22|Nice";name="John"')
1.8754496594662555

    >>> timeit('line.split("|")[0] == name', 'line="John|22|Nice";name="Jonny"') 
    0.511219799415926

特别是 Padraick

>>> timeit('line.partition("|")[0] == name', 'line="John|22|Nice";name="John"')
0.27333073995099083
>>> timeit('line.split("|", 1)[0] == name', 'line="John|22|Nice";name="John"')
    0.5120651608158937

坦白说-我自己也很惊讶

  with open("in.txt") as f:
    lines = f.readlines()
    name = raw_input("Enter the name of the person you want to delete: ").lower() + "|"
    ln = len(name)
    for ind, line in enumerate(lines):
        if name == line[:ln].lower():
            lines[ind:ind+1] = []
            break
    with open("in.txt","w") as out:
        out.writelines(lines)

如果你想删除所有 John 等..不要中断,继续循环和写入,就目前而言,我们会删除我们找到的第一个 "John"。最快的方法就是索引。