首页 > 解决方案 > 在python中使用gmail api从电子邮件中提取表格

问题描述

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

这是电子邮件快照

在此处输入图像描述

我想处理表,但找不到在 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>

有没有一种方法可以让我获得可以在熊猫中导入的表格数据

标签: pythonpandasbeautifulsoupgmail-apigoogle-api-python-client

解决方案


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

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

推荐阅读