Python 问题在于变量定义。我不知道如何解决
我正在尝试使用正则表达式从文本文件中提取日期。 文本文件中日期行的示例:Python 问题在于变量定义。我不知道如何解决,python,regex,python-3.6,Python,Regex,Python 3.6,我正在尝试使用正则表达式从文本文件中提取日期。 文本文件中日期行的示例: 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 ):
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(年、月、日、int(小时)、int(分钟))都是一行,但在我格式化它时,它看起来不是这样的,所以我认为这将有助于指出这一点
我知道问题在于dt=无。当我让它打印出我正在提取的文件目录中的所有日期时,它只会打印出与我的日期相同数量的文件
预期结果是dt变量被创建为空,并在遇到日期时替换为日期。
所以对于这个例子,我想要的是:1530121990
行:
1530Z 1990年2月1日
并且能够从我分配给它的给定对象调用月、日、年、时间。这里有一个解决方案,我更改了regex模式。我将其替换为
date\u matcher=re.compile(r)((\d{4})[Z]).*(\d{1,2})。(\w{3})。(\d{4})
,这将为您提供所需的结果
从这里开始,我使用re.sub
来简单地使日期看起来像您想要的(即,比原始日期更可读)。它删除Z字符,将月份名称更改为相应月份数,并在字符串中间移除多余的空白。
重新导入
从时间导入strtime
从日期时间导入日期时间
数据匹配器=重新编译('^(\s\s[0-2]))
date_matcher=re.compile(r“(\d{4})[Z]).*(\d{1,2})。(\w{3})。(\d{4})”
def get_数据_行(路径):
#我们放置数据行的位置(无标题行)
数据线=[]
#对于os.walk(路径)中的根、目录和文件:
#打印oot、dirs、dirs2、文件
如果os.path.isfile(str(path))和(str(path.endswith('.dat')):
打开(路径)作为f:
dt=无
对于f中的行:
#检查那一行不是空的
如果line.strip():
#编译的匹配器将返回一个匹配对象
#如果未找到匹配项,则返回null。
结果=数据匹配器匹配(行)
如果结果为:
dt=re.sub(r'((\d{4})[Z]),r'\2',行)#删除Z字符
月=日期匹配器。匹配(行)。组(4)
dt=re.sub(r'\b(\w{3})\b',str(strtime(month,'%b').tm_mon),line)#将月份名称更改为数字
dt=re.sub(r'\s+','',dt)#删除额外的空白
数据行追加((行,dt))
打印('数据行:',数据行)
其他:
line=[w代表第行中的w.split()如果为w]
日期=行[-4:]
如果len(日期)==4:
时间、日、月、年=日期
#打印日期
#确定日期
时间=时间。替换('Z','')
日=整数(日)
月份=strtime(月份,'%b')。tm_mon
年份=整数(年)
小时,分钟=re.findall(“..”,时间)
dt=日期时间(年、月、日、整数(小时)、整数(分钟))
数据行追加((行,dt))
返回数据行
因此函数“def get_data_line(path):”也会获取数据行。我有两个不同的正则表达式匹配器。这个:data_matcher=re.compile('^(\s\s[0-2])是用于数据的。明白了。我将调整代码以反映这一点。如果我的答案对你有效,请将其标记为已接受。我肯定将其标记为已接受。修复regex后,它立即打印出正确的日期。我还忘了python从0开始定义我正在提取的其他变量,而不是“columns in rows”的1,例如:height=row[0:5],而不是row[1:6],看起来它开始提取正确的行,但切断了一些数据。