如何将getEmails函数的多次输出合并为统一列表并存入DataFrame
解决方案
当前代码的核心问题:每次匹配到符合条件的发件人时,都会在逻辑块内新建临时列表results,仅存储当前匹配结果后打印,临时列表会随循环迭代被销毁,且函数无返回值,外部无法拿到所有聚合结果。
推荐实现方案(函数返回法,无全局变量污染)
import os import pickle import base64 import re from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from bs4 import BeautifulSoup import pandas as pd # 请自行替换为你的SCOPES配置 SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] def getEmails(): # 函数内部初始化总列表,收集所有匹配结果 all_sites = [] creds = None if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES) creds = flow.run_local_server(port=0) with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('gmail', 'v1', credentials=creds) result = service.users().messages().list(userId='me').execute() messages = result.get('messages') for msg in messages: txt = service.users().messages().get(userId='me', id=msg['id']).execute() try: payload = txt['payload'] headers = payload['headers'] sender = None for d in headers: if d['name'] == 'From': sender = d['value'] parts = payload.get('parts')[0] data = parts['body']['data'].replace("-","+").replace("_","/") decoded_data = base64.b64decode(data) soup = BeautifulSoup(decoded_data , "lxml") page = soup.find('p', text=re.compile('has been listed on ')).getText() site = None if page: match = re.search(r'has been listed on (\b\w+\b) ', str(page)) if match: site = match.group(1) if sender == 'Cryptocurrency Alerting <alerts@mail.cryptocurrencyalerting.com>' and site: # 匹配到结果直接追加到总列表 all_sites.append([site]) print([site]) except: pass # 函数执行完成后返回全量聚合列表 return all_sites # 调用函数接收聚合后的合法列表 results_list = getEmails() # 可直接生成DataFrame df = pd.DataFrame(results_list, columns=['exchange'])
补充说明
- 原冗余的
Convert函数已移除,直接通过正则分组提取交易所名称即可,无需额外拆分字符串 - 此前尝试的
k = print(...)写法无效,因为print仅负责将内容输出到控制台,本身无返回值,变量k会一直为None,无法通过该方式收集结果 - 如果坚持要用外部变量收集,可在函数外定义总列表后,在函数内声明
global 总列表名后追加结果,该方式存在全局变量污染风险,不推荐使用
内容的提问来源于stack exchange,提问作者crispYpickle
相关产品推荐
相关产品推荐

