python - 查找一行下一行

标签 python python-3.x

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

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

聊天是这样的(出于隐私原因,消息被审查):

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 中输出“Name FirstName”,我想要做的是输出 Results.txt 中 Name FirstName 之后的行。任何线索将不胜感激!提前致谢。

最佳答案

你可以这样做:

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/

相关文章:

python - 如何使用漂亮的汤从 html 文档中获取 <text> 标签

python - pgAdmin4 错误 : ModuleNotFoundError: No module named 'email_validator'

python - 将日期时间转换为时间戳并再次转换回来

python - 多个条件下的数据框切片 Python

python - 未知命令 : shell_plus and --settings

python - 从 SciPy 稀疏 Coo 矩阵填充 Pandas SparseDataFrame

python - 如何将 PyTorch 中的 torchscript 模型转换为普通的 nn.Module?

python - 无法添加文件中的数字

python - 等效于 Python 的 OpenCV 中的 FileNotFoundError

python - 如何分组并绘制它