日期时间正则表达式帮助

大家好,开发人员,
我是一个初学者,在编写一个日期和时间的正则表达式需要帮助从一些html文件中提取。在下面的代码中,我遍历了名为Event的文件夹中的html文件,并使用美丽汤打印带有h1标记的标题。这些html页面还包含不同格式的日期和时间。我也想获取并显示此信息。这些html文档中的不同日期格式如下:
2012年11月21日至27日
2012年12月1日
2012年11月30日-12月2日
2012年11月26日
有人能帮我从这些html文档中提取这些格式吗?
下面是我的代码,用于遍历文件并从这些html文件中获取h1:
代码:

选择 | 换行 | 行号
  1.  
  2.     import re
  3.     import os
  4.     from bs4 import BeautifulSoup
  5.  
  6.     for subdir, dirs, files in os.walk("/home/himanshu/event/"):
  7.         for fle in files:
  8.             path = os.path.join(subdir, fle)    
  9.             soup = BeautifulSoup(open(path))
  10.  
  11.             print (soup.h1.string)
  12.  
  13.             #Date and Time detection
# 回答1


您可以使用组合来编译struct_time对象列表
请注意

时间
模块。

选择 | 换行 | 行号
  1. import time
  2. import re
  3.  
  4. patt = re.compile(r"^(\d{1,2}) - (.+)|^(\d{1,2} [a-zA-Z]{3}) - (.+)")
  5.  
  6. date_format = "%d %b %Y"
  7. date_format1 = "%d %m %Y"
  8.  
  9. dates = ["21 - 27 Nov 2012", "1 Dec 2012", "30 Nov - 2 Dec 2012", "26 Nov 2012"]
  10.  
  11. output = []
  12.  
  13. for d in dates:
  14.     try:
  15.         m = patt.match(d)
  16.         if m:
  17.             if m.groups()[0]:
  18.                 end_date = time.strptime(m.groups()[1], date_format)
  19.                 output.append((time.strptime("%s %s %s" % (m.groups()[0],
  20.                                                            end_date.tm_mon,
  21.                                                            end_date.tm_year),
  22.                                              date_format1), end_date))
  23.             elif m.groups()[2]:
  24.                 end_date = time.strptime(m.groups()[3], date_format)
  25.                 output.append((time.strptime("%s %s" % (m.groups()[2],
  26.                                                         end_date.tm_year),
  27.                                              date_format), end_date))
  28.         else:
  29.             output.append(time.strptime(d, date_format))
  30.     except ValueError, e:
  31.         print "ValueError:", e
  32.  
  33. for item in output:
  34.     if isinstance(item, tuple):
  35.         print "  From:", item[0]
  36.         print "    To:", item[1]
  37.     else:
  38.         print item

标签: python

添加新评论