簡體   English   中英

在python中計算日期出現次數?

[英]Counting date occurrences in python?

我目前正在嘗試計算聊天記錄中日期發生的次數,例如,我正在讀取的文件可能看起來像這樣:

*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))

最簡單的方法是使用正則表達式並獲取日志文件中日期模式的計數。 它也會更快。

如果您知道日期和時間將在消息的開頭用括號括起來(即,在包含日期和時間的括號之前不會出現括號(...): :):

*username* (mm/dd/yyyy hh:mm:ss): *message here*

然后,您可以根據括號提取:

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-except中以繼續到下一行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM