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

标签 python list pandas dataframe

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

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/

相关文章:

Python 对字典列表值求和进行排序

python - 在Python中,如何将数据从Excel复制到网站?

python - 在字符串中查找并替换多个逗号/空格实例,Python

python - 如果没有返回异常,则传递异常并引发错误的方法

C++ 记住指向已分配字符串的指针

python - 二维列表的排列 (Python)

python - 压缩 Pandas 数据框中的列

python - 列中重复值之间的条件

python - 收到 Cassandra 已准备好的声明

python - 当 pytest 与 REST 框架交互时,PATCH 和 PUT 无法按预期工作