获取长路径中的文件名的Python正则表达式
我需要分析一些日志文件,内容大概是这样的。我想提取三部分数据:
- 时间
- 目录的一部分,在这个例子中,就是输入文件中的ABC和DEF。
- 输入文件中的文件名,比如2C.013000000B.dat、20100722B.TXT、20100722D1-XYZ.TXT和2C.250B。
我使用了这个正则表达式,但它没能提取到第三部分。
(\d\d:\d\d:\d\d).*(ABC|DEF).*\\(\d\w\.?\w\..*)\soutput.*
任何建议都非常感谢。
08:38:36 TestModule - [INFO]result success !! ftp_site=ftp.test.com file_dir=CPY input file=\root\level1\level2-ABC\2C.013000000B.dat output file=c:\local\project1\data\2C.013000000B.dat.ext
06:40:37 TestModule - [INFO]result success !! ftp_site=ftp.test.com file_dir=CPY input file=\root\level1\level2-ABC\20100722B.TXT output file=c:\local\project1\data\20100722B.TXT.ext
06:40:39 TestModule - [INFO]result success !! ftp_site=ftp.test.com file_dir=CPY input file=\root\level1\level2-DEF\20100722D1-XYZ.TXT output file=c:\local\project1\data\20100722D1-YFP.TXT.ext
06:40:42 TestModule - [INFO]result success !! ftp_site=ftp.test.com file_dir=CPY input file=\root\level1\level2-DEF\2C.250B output file=c:\local\project1\data\2C.250B.ext
祝好
爱德华
6 个回答
1
你可以通过简单的字符串处理来做到这一点。
f=open("file")
for line in f:
date,b = line.split("input")
print "time: " , date.split()[0]
input_path = b.split("output")[0]
tokens=input_path.split("\\")
filename=tokens[-1]
directory=tokens[-2].split("-")[-1]
print filename, directory
f.close()
2
使用split这个方法是个不错的主意。如果你真的想用正则表达式,我会这样做:
(\d\d:\d\d:\d\d).*?input file=.*?(ABC|DEF)\\\\(.*?)\soutput
你可以在 这里 测试一下
3
正则表达式在解决像解析日志文件记录这样的任务时非常有效。MarcoS的回答很好地解决了你眼前的问题。不过,另一种方法是写一个可以重复使用的通用函数,这个函数可以把日志文件记录拆分成不同的部分,并返回一个包含所有这些解析后部分的匹配对象。一旦拆分开来,就可以很容易地对这些部分进行测试,以检查各种要求(比如输入文件路径必须以ABC
或DEF
结尾)。下面是一个包含这样一个函数的Python脚本:decomposeLogEntry()
,并演示了如何用它来解决你的问题:
import re
def decomposeLogEntry(text):
r""" Decompose log file entry into its various components.
If text is a valid log entry, return regex match object of
log entry components strings. Otherwise return None."""
return re.match(r"""
# Decompose log file entry into its various components.
^ # Anchor to start of string
(?P<time>\d\d:\d\d:\d\d) # Capture: time
\s+
(?P<modname>\w+?) # Capture module name
\s-\s\[
(?P<msgtype>[^]]+) # Capture message type
\]
(?P<message>[^!]+) # Capture message text
!!\sftp_site=
(?P<ftpsite>\S+?) # Capture ftp URL
\sfile_dir=
(?P<filedir>\S+?) # Capture file directory?
\sinput\sfile=
(?P<infile> # Capture input path and filename
(?P<infilepath>\S+)\\ # Capture input file path
(?P<infilename>[^\s\\]+) # Capture input file filename
)
\soutput\sfile=
(?P<outfile> # Capture input path and filename
(?P<outfilepath>\S+)\\ # Capture output file path
(?P<outfilename>[^\s\\]+) # Capture output file filename
)
\s* # Optional whitespace at end.
$ # Anchor to end of string
""", text, re.IGNORECASE | re.VERBOSE)
# Demonstrate decomposeLogEntry function. Print components of all log entries.
f=open("testdata.log")
mcnt = 0
for line in f:
# Decompose this line into its components.
m = decomposeLogEntry(line)
if m:
mcnt += 1
print "Match number %d" % (mcnt)
print " Time: %s" % m.group("time")
print " Module name: %s" % m.group("modname")
print " Message type: %s" % m.group("time")
print " Message: %s" % m.group("message")
print " FTP site URL: %s" % m.group("ftpsite")
print " Input file: %s" % m.group("infile")
print " Input file path: %s" % m.group("infilepath")
print " Input file name: %s" % m.group("infilename")
print " Output file: %s" % m.group("outfile")
print " Output file path: %s" % m.group("outfilepath")
print " Output file name: %s" % m.group("outfilename")
print "\n",
f.close()
# Next pick out only the desired data.
f=open("testdata.log")
mcnt = 0
matches = []
for line in f:
# Decompose this line into its components.
m = decomposeLogEntry(line)
if m:
# See if this record meets desired requirements
if re.search(r"ABC$|DEF$", m.group("infilepath")):
matches.append(line)
f.close()
print "There were %d matching records" % len(matches)
这个函数不仅能提取出你感兴趣的各个部分,还会验证输入,拒绝格式不正确的记录。一旦写好并调试完毕,这个函数可以被其他需要分析日志文件的程序重复使用,以满足其他要求。
下面是这个脚本在你的测试数据上运行后的输出:
r"""
Match number 1
Time: 08:38:36
Module name: TestModule
Message type: 08:38:36
Message: result success
FTP site URL: ftp.test.com
Input file: \root\level1\level2-ABC\2C.013000000B.dat
Input file path: \root\level1\level2-ABC
Input file name: 2C.013000000B.dat
Output file: c:\local\project1\data\2C.013000000B.dat.ext
Output file path: c:\local\project1\data
Output file name: 2C.013000000B.dat.ext
Match number 2
Time: 06:40:37
Module name: TestModule
Message type: 06:40:37
Message: result success
FTP site URL: ftp.test.com
Input file: \root\level1\level2-ABC\20100722B.TXT
Input file path: \root\level1\level2-ABC
Input file name: 20100722B.TXT
Output file: c:\local\project1\data\20100722B.TXT.ext
Output file path: c:\local\project1\data
Output file name: 20100722B.TXT.ext
Match number 3
Time: 06:40:39
Module name: TestModule
Message type: 06:40:39
Message: result success
FTP site URL: ftp.test.com
Input file: \root\level1\level2-DEF\20100722D1-XYZ.TXT
Input file path: \root\level1\level2-DEF
Input file name: 20100722D1-XYZ.TXT
Output file: c:\local\project1\data\20100722D1-YFP.TXT.ext
Output file path: c:\local\project1\data
Output file name: 20100722D1-YFP.TXT.ext
Match number 4
Time: 06:40:42
Module name: TestModule
Message type: 06:40:42
Message: result success
FTP site URL: ftp.test.com
Input file: \root\level1\level2-DEF\2C.250B
Input file path: \root\level1\level2-DEF
Input file name: 2C.250B
Output file: c:\local\project1\data\2C.250B.ext
Output file path: c:\local\project1\data
Output file name: 2C.250B.ext
There were 4 matching records
"""