求python脚本,从txt检索出特定字符的行(有很多行,行里面有记录的时间...
发布网友
发布时间:2022-04-24 15:36
我来回答
共2个回答
热心网友
时间:2022-04-18 21:57
逐行匹配。对于每行可以首先使用find来确定该行中有没有特定字符。如果有,则根据正则表达式从中提取时间字符。
以下举一个例子,假设特定字符串为name,时间格式为xxxx-xx-xx。
def main():
import re
time_format = "\d+-\d+-\d+" #时间格式
special_string = "name" #特定字符串
pattern = re.compile(time_format)
txt_content = open("test.txt", "r")
for line in txt_content:
l = line.strip()
if l.find(special_string)>=0: #如果有特定字符串
print l #打印对应的行
match =pattern.match(l) #如果有匹配的时间格式
if match:
print match.group() #打印对应的时间
if __name__ == '__main__':
main()
样例test.txt为
2014-2-11 Your behavior is causing our name to be dragged through the mud.
2014-2-12 I am so happy to get munificent birthday presents from my friends.
2014-2-13 He's the boss in name only, because I issue all the orders.
2014-2-14 We are happy to give the proct our full endorsement.
2014-2-15 His name leaped out at me from the book.
2014-2-16 We'll be happy to help if you need us.
输出结果为
2014-2-11 Your behavior is causing our name to be dragged through the mud.
2014-2-11
2014-2-13 He's the boss in name only, because I issue all the orders.
2014-2-13
2014-2-15 His name leaped out at me from the book.
2014-2-15
追问21:57:41.059-[DEBUG]-[M1]-[D7]-LigeEND Test Block 1/12 - test start time:2013-12-18 21:57:16 ms - test end time:2013-12-18 21:57:41 ms
需要 D7 1/12 21:57:16 21:57:41
追答
修改一下字符串和时间格式即可。
def main():
import re
time_format = "\d+:\d+:\d+ " #时间格式
special_string1 = "D7" #特定字符串
special_string2 = "1/12" #特定字符串
pattern = re.compile(time_format)
txt_content = open("test.txt", "r")
for line in txt_content:
l = line.strip()
if l.find(special_string1)>=0: #如果有特定字符串1
if l.find(special_string2)>=0: #如果有特定字符串2
match =pattern.findall(l) #如果有匹配的时间格式
if match:
for i in match:
print i #打印对应的时间
热心网友
时间:2022-04-18 23:15
你至少应该贴几行你文件的内容吧?
时间什么格式啊?