【发布时间】:2017-10-01 08:20:48
【问题描述】:
我有一个包含聊天记录的大 txt 文件,我的目标是提取不同的组件并创建一个 Pandas Df 来存储在其中。聊天示例如下:
***************************************************** Session:123456 Chat Date: 2017-05-01T08:01:45+00:00 Chat exec name: Sam Member name: Sara 2017-05-01T08:01:45+00:00 Sara: I need help on element A 2017-05-01T08:01:47+00:00 Sam: Sure I can help you on this one 2017-05-01T08:01:48+00:00 Sara: Is there a better product 2017-05-01T08:01:48+10:00 Sam: Sure we have a lot of new products 2017-05-01T08:01:49+18:00 Sara: Can you let me know 2017-05-01T08:01:51+20:00 Sam: Here is the solution 2017-05-01T08:01:52+00:00 Sara: Thanks for this 2017-05-01T08:01:52+11:00 Sam: Have a Nive day Bye!! ***************************************************** Session:234567 Chat Date: 2017-05-02T18:00:30+00:00 Chat exec name: PAUL Member name:CHRIS 2017-05-02T18:00:30+00:00 CHRIS: I need help on element A 2017-05-02T18:02:30+00:00 PAUL: Sure I can help you on this one 2017-05-02T18:02:39+00:00 CHRIS: Is there a better product 2017-05-02T18:04:01+00:00 PAUL: Sure we have a lot of new products 2017-05-02T18:04:30+00:00 CHRIS: Can you let me know 2017-05-02T18:08:11+00:00 PAUL: Here is the solution 2017-05-02T18:08:59+00:00 CHRIS: Thanks for this 2017-05-02T18:09:11+00:00 PAUL: Have a Nice day Bye!! *****************************************************
如果我能够创建包含列的表:
Session、ChatDate、ChatExecName、Membername、Time、Person、Sentence
前 4 列应重复完整的聊天块。除了分隔符是固定的,它们永远不会改变。
我已经尝试过了,但这会将所有块一起返回,有人可以帮忙吗。
import re
def GetTheSentences(infile):
Delim1 = '*****************************************************'
Delim2 = '*****************************************************'
with open(infile) as fp:
for result in re.findall('Delim1(.*?)Delim2', fp.read(), re.S):
print (result)
和
import re
def GetTheSentences2(file):
start_rx =re.compile('*****************************************************')
end_rx = re.compile('*****************************************************')
start = False
output = []
with open(file, encoding="latin-1") as datafile:
for line in datafile.readlines():
if re.match(start_rx, line):
start = True
elif re.match(end_rx, line):
start = False
if start:
output.append(line)
print (output)
【问题讨论】:
-
这看起来像是解析器的工作,而不仅仅是正则表达式。
-
你能指导我完成示例代码/解决方案
-
并非如此。我对这个主题的了解已经过时了。我以前用过野牛。只需谷歌“解析器”并选择适合您的方法。
标签: regex python-3.x