[英]Deleting line from file by containing a specific string is not working in 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是一个矫kill过正,简单的比较就可以
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
坦率地说-我很惊讶
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”。 最快的方法是仅索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.