gpt4 book ai didi

python - 从列表中拆分聊天记录

转载 作者:太空宇宙 更新时间:2023-11-03 14:56:04 25 4
gpt4 key购买 nike

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

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',
]

我正在尝试获取 Start 和 End 之间的所有内容,将 From 和 To 指定为表头,并将中间的消息作为正文。

最终目标是将其推送到 pandas 数据框。

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

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

最佳答案

您可以使用:

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

关于python - 从列表中拆分聊天记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42501967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com