【问题标题】:Python filtering and selecting from listPython过滤和从列表中选择
【发布时间】:2014-02-12 03:20:51
【问题描述】:

我需要创建一个 python 函数来打开一个文件,读取文本,然后在 Python GUI 上输出任何包含日期的条目。有效日期的示例包括“1/30/10”、“1/30/2010”、“1-30-2010”、“01-30-2010”、“30.1.2010”、“30. 1. 2010”和“2010-01-30”。它应该很少有误报,例如“13010”、“01302010”或“30-30-10”作为日期。

我目前拥有的是这个

import sys

def main():
    infile = open('testdate.txt', 'r')

    for line in infile:
        words = line.split()
        for date in words:
            if ____ in date:
                print date


    infile.close()

main()

我知道line.split() 函数能够分隔文本文件中的所有条目。我不确定的是如何遍历这个新列表并且只接受日期。我将如何只过滤日期?

【问题讨论】:

  • 看看datetime.strptime。列出所有可能的日期格式(在文件中)并尝试解析;如果解析成功,打印。
  • 我将如何使用 datetime.strptime(date_string, format)?我猜我需要导入 datetime,那么 date_string 到底是什么?当我遍历“单词”中的项目时,这是我正在查看的变量吗?对于格式,我该如何使用上述格式?
  • 这是一个关于使用自制和第三方解析器解析多种格式日期的问题,其中包含一些很好的答案。除此之外,看起来你在正确的轨道上。 stackoverflow.com/questions/7048828/…
  • 谢谢!我会看看那个。

标签: python list filtering


【解决方案1】:

找出所有可能的格式并尝试解析它们。这可能会有所帮助:

>>> from datetime import datetime
>>> possible_fmts = ["%m/%d/%y","%m/%d/%Y","%m-%d-%y","%m-%d-%Y","%d.%m.%Y","%d. %m. %Y","%Y-%m-%d"]
>>> test_text = "1/30/10,1/30/2010,1-30-2010,01-30-2010,30.1.2010,30. 1. 2010,2010-01-30"
>>> for date_token in test_text.split(','):
        for fmt in possible_fmts:
            try:
                print datetime.strptime(date_token, fmt)
                break
            except ValueError, e:
                pass


2010-01-30 00:00:00
2010-01-30 00:00:00
2010-01-30 00:00:00
2010-01-30 00:00:00
2010-01-30 00:00:00
2010-01-30 00:00:00
2010-01-30 00:00:00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 2012-09-15
    • 1970-01-01
    • 2011-02-11
    相关资源
    最近更新 更多