【问题标题】:Extracting table from email using gmail api in python在python中使用gmail api从电子邮件中提取表格
【发布时间】:2021-06-04 23:14:56
【问题描述】:

我想从邮件中提取表格,邮件在邮件客户端查看时显示表格

这是电子邮件快照

我想处理表格,但找不到在 python 代码中获取它的方法

这里是原始数据的摘录

decoded_data = base64.b64decode(data)

正在显示 b'a d g\r\nb e h\r\nc f j\r\na d\r\nb e h\r\nc f j\r\n\r\nBest Regards,\r\nVikrant Pawar\r\n'

虽然汤很喜欢

soup = BeautifulSoup(decoded_data, "lxml")

它显示

<html><body><p>a d g
b e h
c f j
a d
b e h
c f j

Best Regards,
Vikrant Pawar
</p></body></html>

有没有办法让我可以在 pandas 中导入表格数据

【问题讨论】:

    标签: python pandas beautifulsoup gmail-api google-api-python-client


    【解决方案1】:

    您可以从中拆分数据并形成表格列表:

    from bs4 import BeautifulSoup
    import pandas as pd
    
    text = """
    <html><body><p>a d g
    b e h
    c f j
    a d
    b e h
    c f j
    
    Best Regards,
    Vikrant Pawar
    </p></body></html>
    """
    
    soup = BeautifulSoup(text, 'lxml')
    data = soup.p.text
    list_of_tables = data.split('\n')
    # -> ['a d g', 'b e h', 'c f j', 'a d', 'b e h', 'c f j', '', 'Best Regards,', 'Vikrant Pawar', '']
    

    注意如果有额外的\r\n,你应该用data.split('\n\r')分开。现在您可以获得形成 pandas df 所需的部分。假设您只想要“Best Regards”之前的部分。为此,我们首先需要对列表进行切片,然后拆分每个元素以形成 pandas df:

    list_of_tables = [each.split() for each in list_of_tables[:6]]
    # -> [['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'j'], ['a', 'd'], ['b', 'e', 'h'], ['c', 'f', 'j']]
    

    现在我们要做的就是形成数据框:

    df = pd.DataFrame(list_of_tables)
    

    最终结果如下所示:

       0  1     2
    0  a  d     g
    1  b  e     h
    2  c  f     j
    3  a  d  None
    4  b  e     h
    5  c  f     j
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-25
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2019-04-01
      • 2019-02-10
      • 2018-11-03
      • 2023-03-14
      相关资源
      最近更新 更多