在python中计算日期事件?
我目前正在尝试计算聊天日志中出现日期的次数,例如,我正在读取的文件可能如下所示:在python中计算日期事件?,python,tkinter,counter,Python,Tkinter,Counter,我目前正在尝试计算聊天日志中出现日期的次数,例如,我正在读取的文件可能如下所示: *username* (mm/dd/yyyy hh:mm:ss): *message here* 但是,我需要将日期与时间分开,因为我目前将它们视为一个。我目前正在努力解决我的问题,所以任何帮助都是感激的。下面是一些示例代码,我目前正在使用这些代码来尝试使日期计数正常工作。我目前正在使用一个计数器,但我想知道是否有其他方法来计算日期 filename = tkFileDialog.askopenfile(file
*username* (mm/dd/yyyy hh:mm:ss): *message here*
但是,我需要将日期与时间分开,因为我目前将它们视为一个。我目前正在努力解决我的问题,所以任何帮助都是感激的。下面是一些示例代码,我目前正在使用这些代码来尝试使日期计数正常工作。我目前正在使用一个计数器,但我想知道是否有其他方法来计算日期
filename = tkFileDialog.askopenfile(filetypes=(("Text files", "*.txt") ,))
mtxtr = filename.read()
date = []
number = []
occurences = Counter(date)
mtxtformat = mtxtr.split("\r\n")
print 'The Dates in the chat are as follows'
print "--------------------------------------------"
for mtxtf in mtxtformat:
participant = mtxtf.split("(")[0]
date = mtxtf.split("(")[-1]
message = date.split(")")[0]
date.append(date1.strip())
for item in date:
if item not in number:
number.append(item)
for item in number:
occurences = date.count(item)
print("Date Occurences " + " is: " + str(occurences))
最简单的方法是使用regex并计算日志文件中的日期模式。它也会更快。如果您知道日期和时间将被括在消息开头的括号中(即,在包含日期和时间的括号之前不会看到任何括号)(…):):
*用户名*(mm/dd/yyyy hh:mm:ss):*此处消息*
然后您可以根据参数进行提取:
import re
...
parens = re.compile(r'\((.+)\)')
for mtxtf in mtxtformat:
match = parens.search(mtxtf)
date.append(match.group(1).split(' ')[0])
...
注意:如果消息本身包含参数,则这可能不仅仅匹配所需的参数(mm/dd/yyyy hh:mm:ss)。执行match.group(1).split(“”)[0]
仍将为您提供所需的信息,前提是在日期时间信息(对于当前行)之前的括号中没有包含任何信息
注2:理想情况下,将其包含在try中,但如果当前行不包含有用信息,则继续下一行