我正在为自己编写一个小程序,但是在查找新文件中特定行下的写行时遇到了问题。

更具体地说,我有一个基本上是聊天记录的文件,第一行是一个人的名字,第二行是消息的名字,第三行是另一个人的名字,等等。

聊天是这样进行的(出于隐私原因对邮件进行审查):

Name1 Firstname1
Message sent by Name1 Firstname1
Name2 Firstname2
Message sent by Name2 Firstname2
Name1 Firstname1
Message sent by Name1 Firstname1
Name1 Firstname1
Message sent by Name1 Firstname1


如您所见,顺序可以是随机的,因为某人可以连续发送多个消息。

我试图做到这一点:

import re

def Sep(Source, OutputA):
    with open(Source, 'r', encoding='utf8', errors='ignore') as fdin:
        temp = fdin.readlines()
    regex = re.compile(r"^(Name)+ (FirstName)")
    result = [x for x in temp if regex.search(x)]
    with open(OutputA, 'w', encoding='utf8', errors='ignore') as fdout:
        fdout.writelines(result)

Sep('chat.txt','Results.txt')


此结果在我的Results.txt中输出“名称名字”,我想要做的就是在Results.txt中的名称名字之后输出该行。任何线索将不胜感激!提前致谢。

最佳答案

您可以这样做:

import re

def Sep(Source, OutputA, user_name, user_firstname):
    with open(Source, 'r', encoding='utf8', errors='ignore') as fdin:
        text = fdin.read()

    matches = re.finditer("^({}) ({})\n(.*)".format(user_name,user_firstname),text, re.MULTILINE)
    with open(OutputA, 'w', encoding='utf8', errors='ignore') as fdout:
        for match in matches:
            fdout.write(match.group(3))
            fdout.write("\n")

Sep('chats.txt','Results.txt', "Name1","Firstname1")


输出:

Message sent by Name1 Firstname1
Message sent by Name1 Firstname1
Message sent by Name1 Firstname1

关于python - 在一条线下找到一条线,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59749862/

10-12 17:22