首页 文章

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

提问于
浏览
0
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 回答

  • 1

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

    name + r'\b'
    

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

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

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

    EDIT

    定时:

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

    坦率地说 - 我很惊讶自己

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

    如果你想删除所有约翰的等等 . 不要打破只是保持循环和写作,因为它代表我们擦除我们找到的第一个“约翰” . 最快的方法就是索引 .

相关问题