用RegEx解析电子邮件并存储在Pandas DataFram中

2024-05-16 12:08:08 发布

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

我的问题是创建足够健壮的代码来解析100封措辞不同的电子邮件中的特定数据。这些电子邮件都是txt格式的,我需要所有这些邮件的相同数据。以下是两个电子邮件示例:

1) Subject: FW: NEFS 11 fish for lease
   From: Claire Fitz-Gerald 
   Date: 11/15/2013 3:02 PM

   NEFS 11 has the following fish for lease:

   -GOM Cod up to 5,000 lbs (live wt) @ 1.40 lbs
   -American Plaice 2,000 lbs      .60 lbs or best offer



2) From: Claire Fitz-Gerald 
   Date: 9/5/2014 9:52 AM
   Subject: NEFS 5 Available Fish

   All,
   NEFS 5 has the following fish available for lease/trade:

     GB EAST cod: 954 lbs @ $0.83
     GB EAST cod: 1,046 lbs to trade for 1,830 lbs GB WEST cod
     GB blackback: 30,000 lbs @ $0.07
     GOM blackback: 800 lbs @ $0.03
     white hake: 6,322 lbs @ $0.13
     pollock: 22,000 lbs @ $0.015
     redfish: 14,000 lbs @ $0.015
     GB yt: 1,873 lbs @ $1.13
     GB yt: 5,127 lbs to trade for 10,254 lbs SNE yt

我需要从所有这些电子邮件中获取的数据如下,以示例1)中的数据为例:

部门:NEFS 11

日期:2013年11月15日

鱼类:墨西哥鳕鱼,美洲鲽鱼

重量:50002000

价格:1.40,0.60

交易,是/否?:目前,我只不过是捕捉一行字“贸易”和打印它在其他地方,待日后处理。在

我的代码运行得还算不错,但是我遇到了几个主要的障碍。我的部门代码有效。我的日期代码有效。在

问题1:我的权重代码扫描文本中的逗号,并捕获逗号附近的数字。大多数权重值都在1000以上,但不是所有的权重值都在1000以上,这会在以后我试图将所有权重值对齐时破坏我的数据。我想知道是否有更明智、更有效的方法来解析这些文件中的权重?在

问题2:我的鱼种和价格代码正确识别鱼和$,但在打印时没有对它们进行界定:

^{pr2}$

……这就是为什么我选择熊猫来整理和整理所有的数据,这几乎是完美的,但出于一些奇怪的原因,每次都会在无序的随机位置打印物种,如下所示:

         0            1           2              3        4            5  \
0  pollock  GB EAST cod  white hake  GOM blackback  redfish  GB WEST cod   
1   1,046        1,830      30,000          6,322   22,000       14,000    
2     0.83         0.07        0.03           0.13    0.015        0.015   

              6       7        8  
0  GB blackback   GB yt     None  
1        1,873   5,127   10,254   
2          1.13    None     None  

我的代码无法识别2个权重值(每个权重值低于1000),因此它不正确地将物种与权重对齐。在

其中两条线是Trade,不是简单的租赁,因此没有提供价格……进一步扰乱了数据。这就是为什么我在考虑将这些导出到其他地方,或者稍后解析它们,或者手动执行它们。在

因此,最终这就是我想要完成的:1)这些带有trade的行被捕获并导出,并从我的RegEx搜索中排除。2)使用一种更干净、更精确的方法来获取权重,因为显然我的方法不起作用(可能搜索“磅|磅”并捕获直接位于这些值之前的数字?)。3)所有数据正确对齐的清晰打印输出。在

我意识到这不是一个简单直接的问题,如果这个问题过于开放、模糊或不符合标准,我真的很抱歉,但这是我的困境,我正在寻求帮助或建议。非常感谢你的帮助。在

我的代码:

import os
import email
import re
import numpy as np
import pandas as pd

path = 'Z:\\stuff_text' 

data_frame = {'Species' : [],
                  'Weights' : [],
                  'Prices' : []}

for filename in os.listdir(path):
    file_path = os.path.join(path, filename)
    if os.path.isfile(file_path):
        with open(file_path, 'r') as f:
            pattern = re.compile("Available Quota|American Plaice|CC Yellowtail Flounder|GOM Yellowtail Flounder|GB blackback|GB Cod East|GB East Cod|GB Cod West|GB West Cod|GB Haddock East|GB Haddock West|GB Winter Flounder|GB Yellowtail Flounder|GB yt|GOM Cod|GOM Haddock|GOM Winter Flounder|GOM blackback|Plaice|Pollock|Redfish|SNE Winter Flounder|ME Winter Flounder|SNE Yellowtail Flounder|ME Yellowtail Flounder|White Hake|Witch Flounder|Dabs", re.IGNORECASE)
            email = f.read()
            fish_types = pattern.findall(email)
            fish_types_new = list(set(fish_types))     #makes sure each fish appears only once
            data_frame['Species'].append(fish_types_new)
            print("Fish Species:", ''.join(fish_types_new))

for filename in os.listdir(path):
    file_path = os.path.join(path, filename)
    if os.path.isfile(file_path):
        with open(file_path, 'r') as f:
            pattern = re.compile(r'\d+,\d+ ')
            #pattern = re.compile("Pounds|lbs", re.IGNORECASE)
            email = f.read()
            weights = pattern.findall(email)
            data_frame['Weights'].append(weights)
            if weights:
                print("Weight:", ''.join(weights))

for filename in os.listdir(path):
    file_path = os.path.join(path, filename)
    if os.path.isfile(file_path):
        with open(file_path, 'r') as f:
            pattern = re.compile(r'(?:\d+)?\.\d+')
            #pattern = re.compile("@|up to|$|Price", re.IGNORECASE)
            email = f.read()
            prices = pattern.findall(email)
            data_frame['Prices'].append(prices)
            if prices:
                print("Price:", ''.join(prices))

fish = np.array(fish_types_new), np.array(weights), np.array(prices)
fish_df = pd.DataFrame.from_records(fish)
print(fish_df)

Tags: 数据path代码reforosemailfile