以12小时格式匹配日期和时间

问题描述 投票:0回答:1

我正在按照本教程(https://towardsdatascience.com/build-your-own-whatsapp-chat-analyzer-9590acca9014)来构建WhatsApp分析器。

这是他的教程中的全部代码-

def startsWithDateTime(s):
    pattern = '^([0-2][0-9]|(3)[0-1])(\/)(((0)[0-9])|((1)[0-2]))(\/)(\d{2}|\d{4}), ([0-9][0-9]):([0-9][0-9]) -'
    result = re.match(pattern, s)
    if result:
        return True
    return False

def startsWithAuthor(s):
    patterns = [
        '([\w]+):',                        # First Name
        '([\w]+[\s]+[\w]+):',              # First Name + Last Name
        '([\w]+[\s]+[\w]+[\s]+[\w]+):',    # First Name + Middle Name + Last Name
        '([+]\d{2} \d{5} \d{5}):',         # Mobile Number (India)
        '([+]\d{2} \d{3} \d{3} \d{4}):',   # Mobile Number (US)
        '([+]\d{2} \d{4} \d{7})'           # Mobile Number (Europe)
    ]
    pattern = '^' + '|'.join(patterns)
    result = re.match(pattern, s)
    if result:
        return True
    return False

def getDataPoint(line):
    # line = 18/06/17, 22:47 - Loki: Why do you have 2 numbers, Banner?

    splitLine = line.split(' - ') # splitLine = ['18/06/17, 22:47', 'Loki: Why do you have 2 numbers, Banner?']

    dateTime = splitLine[0] # dateTime = '18/06/17, 22:47'

    date, time = dateTime.split(', ') # date = '18/06/17'; time = '22:47'

    message = ' '.join(splitLine[1:]) # message = 'Loki: Why do you have 2 numbers, Banner?'

    if startsWithAuthor(message): # True
        splitMessage = message.split(': ') # splitMessage = ['Loki', 'Why do you have 2 numbers, Banner?']
        author = splitMessage[0] # author = 'Loki'
        message = ' '.join(splitMessage[1:]) # message = 'Why do you have 2 numbers, Banner?'
    else:
        author = None
    return date, time, author, message


parsedData = [] # List to keep track of data so it can be used by a Pandas dataframe
conversationPath = 'chat.txt' 
with open(conversationPath, encoding="utf-8") as fp:

    fp.readline() # Skipping first line of the file (usually contains information about end-to-end encryption)

    messageBuffer = [] # Buffer to capture intermediate output for multi-line messages
    date, time, author = None, None, None # Intermediate variables to keep track of the current message being processed

    while True:
        line = fp.readline() 
        if not line: # Stop reading further if end of file has been reached
            break
        line = line.strip() # Guarding against erroneous leading and trailing whitespaces
        if startsWithDateTime(line): # If a line starts with a Date Time pattern, then this indicates the beginning of a new message
            print('true')
            if len(messageBuffer) > 0: # Check if the message buffer contains characters from previous iterations
                parsedData.append([date, time, author, ' '.join(messageBuffer)]) # Save the tokens from the previous message in parsedData
                messageBuffer.clear() # Clear the message buffer so that it can be used for the next message
                date, time, author, message = getDataPoint(line) # Identify and extract tokens from the line
                messageBuffer.append(message) # Append message to buffer

        else:
            messageBuffer.append(line) # If a line doesn't start with a Date Time pattern, then it is part of a multi-line message. So, just append to buffer

当我插入聊天文件-chat.txt时,我发现列表parsedData为空。浏览完他的代码后,我注意到可能是空白列表的原因。在他的教程中,他的聊天采用这种格式(24小时)-18/06/17, 22:47 - Loki: Why do you have 2 numbers, Banner?,但我的聊天是这种格式(12小时)-[4/19/20, 8:10:57 PM] Joe: How are you doing

原因startsWithDateTime功能无法匹配任何日期和时间。

请如何更改startsWithDateTime函数中的正则表达式格式以匹配我的聊天格式?

python regex python-3.x
1个回答
0
投票

这里有一些问题。首先,您的正则表达式正在以DD / MM / YYYY格式查找日期,但您输入的格式为M / DD / YYYY。其次,方括号在您给出的第一个示例中不存在,成功了,但在第二个示例中存在。第三,在查看正则表达式时,问题不在于12小时v 24小时时间格式本身,而在于您的正则表达式正在搜索严格的2位数小时数字。使用24小时制时,通常在单位数小时中包含前导零(例如,上午8:10时为08:10),但在12小时制中则不是(因此,您的代码将找不到[ C0]。您可以通过从[]更改相关部分来修复正则表达式

8:10

to

([0-9][0-9]):([0-9][0-9])

大括号中的数字表示要查找该字符的示例个数,因此在这种情况下,该表达式将查找一位或两位数,然后是一个冒号,然后是两位数。

那么最后的正则表达式必须是

([0-9]{1,2}):([0-9]{2})

示例:

^\[(\d{1,2})\/(\d{2})\/(\d{2}|\d{4}), ([0-9]{1,2}):([0-9]{2}):([0-9]{2})\ ([AP]M)\]
© www.soinside.com 2019 - 2024. All rights reserved.