【发布时间】:2019-08-19 22:05:39
【问题描述】:
我正在尝试使用正则表达式从文本文件中提取日期。 文本文件中的日期线示例:
1530Z 1 FEB 1990
使用的正则表达式:
date_matcher = re.compile("^([0-9]{4}[z].[0-9]+.[A-Z]{3}.[0-9]{4})")
我尝试修改我正在使用的代码,然后从正则表达式中“提取”日期和时间。这是代码:
# get just the data lines, without headers.
def get_data_lines( path ):
# where we are putting data lines (no header lines)
data_lines = []
#for root, dirs, files in os.walk(path):
#print oot, dirs, dirs2, files
if os.path.isfile(str(path)) and (str(path.endswith('.dat'))):
with open(path) as f:
dt = None
for line in f:
# check that line isn't empty
if line.strip():
# the compiled matcher will return a match object
# or null if no match was found.
result = data_matcher.match(line)
if result:
data_lines.append((line,dt))
else:
dtres = date_matcher.match(line)
if dtres:
line = [ w for w in line.split() if w]
date = line[-4:]
if len(date) == 4:
time, day, month, year = date
# print date
# fix the date bits
time = time.replace('Z','')
day = int(day)
month = strptime(month,'%b').tm_mon
year = int(year)
hour, minutes = re.findall('..',time)
dt = datetime(year,month,day,int(hour),int(minutes))
return data_lines
dt = datetime(year,month,day,int(hour),int(minutes)) 都是一行,但在我格式化它时看起来不是这样,所以我认为这会有助于指出出去。
我知道问题在于 dt = None。当我让它打印出我要提取的文件目录中的所有日期时,它只会为我有日期的文件打印 NONE 。
预期结果是 dt 变量被创建为空,并在遇到日期时被替换为日期。
所以对于这个例子,我想要的是:1530 1 2 1990
对于线路:1530Z 1 FEB 1990
并且能够从我分配给它的给定对象中调用月、日、年、时间。
【问题讨论】:
标签: python regex python-3.6