简体   繁体   中英

Python - Delete Conditional Lines of Chat Log File

I am trying to delete my conversation from a chat log file and only analyse the other persons data. When I load the file into Python like this:

with open(chatFile) as f:
    chatLog = f.read().splitlines()

The data is loaded like this (much longer than the example):

'My Name',
'08:39 Chat data....!',
'Other person's name',
'08:39 Chat Data....',
'08:40 Chat data..., 
'08:40 Chat data...?',

I would like it to look like this:

'Other person's name',
'08:39 Chat Data....',
'08:40 Chat data..., 
'08:40 Chat data...?',

I was thinking of using an if statement with regular expressions:

name = 'My Name'
for x in chatLog:
    if x == name:
        "delete all data below until you get to reach the other 
         person's name"

I could not get this code to work properly, any ideas?

I think you misunderstand what "regular expressions" means... It doesn't mean you can just write English language instructions and the python interpreter will understand them. Either that or you were using pseudocode, which makes it impossible to debug.

If you don't have the other person's name, we can probably assume it doesn't begin with a number. Assuming all of the non-name lines do begin with a number, as in your example:

name = 'My Name'
skipLines = False
results = []
for x in chatLog:
    if x == name:
        skipLines = True
    elif not x[0].isdigit():
        skipLines = False

    if not skipLines:
        results.append(x)
others = []
on = True
for line in chatLog:
    if not line[0].isdigit():
        on = line != name
    if on:
        others.append(line)

You can delete all of your messages using re.sub with an empty string as the second argument which is your replacement string.

Assuming each chat message starts on a new line beginning with a time stamp, and that nobody's name can begin with a digit, the regular expression pattern re.escape(yourname) + r',\\n(?:\\d.*?\\n)*' should match all of your messages, and then those matches can be replaced with the empty string.

import re

with open(chatfile) as f:
    chatlog = f.read()
    yourname = 'My Name'
    pattern = re.escape(yourname) + r',\n(?:\d.*?\n)*'
    others_messages = re.sub(pattern, '', chatlog)
    print(others_messages)

This will work to delete the messages of any user from any chat log where an arbitrary number of users are chatting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM