从lis中拆分聊天记录

2024-09-30 16:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,它基本上是使用下面的代码从即时消息文件中提取的:

with open(input('address here pls: '),'r') as f:
    f = f.readlines()

返回的元素列表如下

> ['=Start=','From: Me','To: You','Hey there','Howre u doing?','=End',
'=Start=','From: You','To: Me','Good!','How bout you?','=End',
]

我正在尝试获取开始和结束之间的所有内容,将From和to指定为表头,并将中间的消息指定为正文。你知道吗

最终目标是将其推送到一个数据帧。你知道吗

下面是我想要得到的结果:

======================================
From|To |Message                     |
======================================
Me  |You|'Hey there Howre you doing?'|
You |Me |'Good! How bout you?'       |

Tags: tofromyou列表starthowendme
1条回答
网友
1楼 · 发布于 2024-09-30 16:20:37

您可以使用:

L = ['=Start=','From: Me','To: You','Hey there','Howre u doing?','=End',
'=Start=','From: You','To: Me','Good!','How bout you?','=End',
]
#create df from L
df = pd.DataFrame({'Message': L})
#create groups by mask and cumulative sum
b = (df.Message == '=Start=').cumsum()

#extract text in From and To
df['From'] = df.Message.str.extract('From: (.*)', expand=False).ffill()
df['To'] = df.Message.str.extract('To: (.*)', expand=False).ffill()

#remove unnecessary rows
out = ['=Start=','=End','From:','To:']
df = df[~df.Message.str.contains('|'.join(out))]
#groupby by Series b and aggregate
df = df.groupby(b).agg({'Message': ' '.join, 'To': 'last', 'From': 'last'})
df = df.reset_index(drop=True)
print (df)
                    Message   To From
0  Hey there Howre u doing?  You   Me
1       Good! How bout you?   Me  You

相关问题 更多 >