regex - 从文本文件中提取信息 block 并创建 Pandas 数据框并存储

标签 regex python-3.x

我有一个包含聊天记录的大 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、成员名称、时间、人员、句子

对于完整的聊天块,应重复前 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)

最佳答案

我当然希望这有帮助:

data = '''*****************************************************
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!!
*****************************************************'''

data = data.split('*****************************************************')
data = [item.split('\n') for item in data if item]
result = []
for group in data:
    group = [item for item in group if item]
    times = []
    people = []
    lines = []
    for item in group:
        if item.startswith('Session'):
            session = item.split(':')[-1]
            print session
        elif item.startswith('Chat Date'):
            chatDate = item.split(':', 1)[-1]
        elif item.startswith('Chat exec'):
            execName = item.split(':')[-1]
        elif item.startswith('Member'):
            memberName = item.split(':')[-1]
        else:
            times.append(item[:25])
            people.append(item[26:].split(':')[0])
            lines.append(item[26:].split(':')[-1])
    for i in range(len(times)):
        result.append([session, chatDate, execName, memberName, times[i], people[i], lines[i]])

import pandas as pd

df = pd.DataFrame(result, columns=['Session', 'ChatDate', 'ChatExecName', 'Membername', 'Time', 'Person', 'Sentence'])

print df

关于regex - 从文本文件中提取信息 block 并创建 Pandas 数据框并存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43761106/

相关文章:

regex - awk 文件中的多个单词正则表达式匹配

regex - 将 url(r'^(?P<pk>[-\w]+)/$') 解码为 Django 中的 path()

python - 如何读取和打印一个ttf文件的内容?

Python 3 & Kivy : React only to double tap "not" single tap

正则表达式匹配多个点

javascript - 如何调整 while 循环中的变量范围以匹配 CoffeeScript 中的所有正则表达式?

正则表达式 - 匹配所有内容,但不匹配字符序列,包括换行符

python - 从 python 脚本自动将命令行输入到运行的 python shell 脚本中

python - 使用python从文本中提取最后一段

python-3.x - 如何从 numpy 数组中输入数据来训练 CNTK 回归模型