删除包含完全字符串的文件中的行(Python)

时间:2015-02-13 22:47:02

标签: python file line

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作为第一个字符串的行元件。

我发现了很多类似的问题,但我的功能包含了所有内容,我无法理解。

2 个答案:

答案 0 :(得分:1)

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

name + r'\b'

但是在你的情况下, re 是一种矫枉过正,简单的比较会做

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

顺便说一下,如果你只需要在开头 - 或结束时拆分一次 - 分区 rpartition 功能是更好的选择

修改

定时:

    >>> 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
坦率地说 - 我很惊讶

答案 1 :(得分:0)

  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)

如果你想删除所有约翰等等。不要打破只是保持循环和写作,因为我们擦除了第一个"约翰"我们发现。最快的方法就是索引。