【问题标题】:Searching and sorting a file in Python在 Python 中搜索和排序文件
【发布时间】:2019-11-28 18:01:26
【问题描述】:

我正在尝试设置一个脚本来查看包含 IP 地址和日期等内容的单个文件。我想提取所有超过 365 天的数据并有一个文本文件可供查看。我不断遇到语法错误等问题。

我尝试过改变

day = eval(line) to day = str(line) but I get
TypeError: can't compare datetime.date to str
#!/bin/env python

from datetime import timedelta
import datetime

limit = datetime.datetime.now() +  timedelta(days=365)
with open('filename') as ifile:
    for line in ifile:
        day = eval(line)
        if day > limit:
            break
formatted_dates = [(item[0], item[1].strptime("%d/%m/%y"), item[2]) for item in sorted_dates]
for date in formatted_dates:
    print ('{}: {}'.format(date))

我想要一个新文件,内容如下:

128.xxx.xxx.xx [%d %m %y] 从最旧到最新。

我不断得到:

File "./scrpitpyth.py", line 9, in <module>
    day = eval(line)
  File "<string>", line 1
  128.xxx.xxx.xx - - [02/Feb/2016:15:00:26 -0700] 
SyntaxError: invalid syntax

我试图解析的数据如下:

128.xxx.xxx.xxx - - [20/Mar/2017:09:54:03 -0600] "POST /work/labor/HTTP/1.1"

128.xxx.xxx.xxx - - [23/Mar/2017:09:54:03 -0600] "GET /work/ HTTP/1.1" 200

128.xxx.xxx.xxx - - [24/Mar/2017:09:56:02 -0600] "GET /work/view/laborcats

【问题讨论】:

  • 正如下面的答案中提到的eval() 是问题所在,但为了提供建议,您能否提供一些您尝试解析的示例文本文件?
  • 刚刚添加它们
  • 怎么强调都不为过:永远不要使用eval()。尤其是在不受信任的输入上。

标签: python file datetime syntax-error


【解决方案1】:

eval 尝试将字符串作为 python 代码执行。您呈现给它的行不是合法的 python 代码,这就是 eval 失败的原因。

您可能希望使用正则表达式来提取日期,详情请参阅 re 模块

https://docs.python.org/3/library/re.html

作为示例,以下模式匹配示例行中给定格式的日期:

>>> pat = re.compile("\d+/\w+/\d+:\d+:\d+:\d+ -?\d+")
>>> pat.search(date_str)
<_sre.SRE_Match object at 0x104982e00>
>>> _.group()
'02/Feb/2016:15:00:26 -0700'
>>> 

【讨论】:

    【解决方案2】:

    我会将此添加为评论,但我的业力太低了。

    通常不建议使用 eval 函数,因为它只是执行传递的任何字符串。在这种情况下,您尝试将字符串 128.xxx.xxx.xx - - [02/Feb/2016:15:00:26 -0700] 作为 python 命令运行。由于这不是有效的python,因此您会失败。

    为了解决这个问题,我建议使用 datetime 库中的 strptime 函数将时间戳字符串转换为 datetime 对象,然后您可以使用此对象进行时间过滤。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 2010-10-06
      • 1970-01-01
      相关资源
      最近更新 更多