Python文字替换为for循环

时间:2018-08-30 02:08:47

标签: python python-3.x

我只是想删除所有日期时间值... 但每次都会从头开始,并以最后一个值刷新文本。如何删除所有时间值?

我的文本文件是hey.txt,这是其中的内容:

time_in_nanos

代码部分:

14:15
24:32
trying
42:56
1:42
for
testing

这是我的发送文件datetimes-doc.txt

import re
filename = "hey.txt"
text = open(filename).read()
n,i,c,x,=(0,0,0,0)
datetimes = []
for number in range(3600):
    n+=1
    b=str(n)
    if n<10:
        b = "0"+str(n)
    elif n==60:
        i+=1
        n=0 
    datetimes.append("%d:%s"%(i,b)) 
for word in datetimes:    
    matches = re.compile(word).finditer(text)
    for match in matches:
        z= match.group(0)
        print(z)
        if z==word:
            open("datetimes-doc.txt","w+").write(text.replace(z,""))
            c+=1
        elif z!=word:
            c+=1
        print("proccess:%d"%c)

这是控制台的一些输出:

14:15
24:32
trying

1:42
for
testing

1 个答案:

答案 0 :(得分:2)

而不是for循环,为什么不呢?

#read entire file's content 
with open('hey.txt') as f:
    content = f.read()

# find time and replace with empty string
new_content = re.sub(r'[0-5]*[0-9]:[0-5]*[0-9]\n','', content)

#write results into file
with open('hey2.txt', 'w') as f:
    f.write(new_content)