列表索引不返回值

List Index is not returning values

我在 Python 中使用 Win32com 访问我的 Outlook 电子邮件,我正在使用正则表达式在我的电子邮件的主题行中搜索案例编号。

例如,一封电子邮件的主题行可能显示为 Hisenburg CASE# 0039484。我至少有 30 封这样的电子邮件。

这是我的代码:

import pandas as pd, os
from pandas import DataFrame as df
import win32com.client as client
import time, datetime, smtplib, imaplib, pathlib, re

outlook = client.Dispatch('Outlook.Application')
namespace = outlook.GetNameSpace('MAPI')
account = namespace.Folders['name@company.com']
inbox = account.Folders['Inbox']
ap = inbox.Folders['Dean Brown']

pattern = re.compile(r'CASE# \d\d\d\d\d\d\d')
for x in message.items:
    b = re.findall(pattern, x.Subject)
    c = []
    for y in range(len(b)):
        c.append(b[y])
        print(c)

当我键入 c 以获取列表中的项目时,出现以下错误: TypeError: 'NoneType' 对象不可订阅

如果我键入 c[1],我会收到以下错误:IndexError: list index out of range

当我的结果 (c) 填充 30 个数字时,为什么我会收到此错误消息?有没有办法填充电子邮件的内容?我该如何解决这个问题?

你收到错误 IndexError: list index out of range 因为你正在开始一个循环:

for y in range(len(b)):

然后,当您将第一项添加到数组中时,您直接在它之后使用尚不存在的 c[1] 询问数组中的 second 项.

c.append(b[y])
print(c[1])

如果要得到第一项,可以将缩进向左缩短一步,并根据列表中的可用结果使用c[0]c[1]

请注意,您不必执行循环机制。

您可以直接使用 re.findall 到 return 字符串列表。

c = re.findall(r"CASE# \d{7}", x.Subject)

我找到了解决办法。我的电子邮件中的内容没有填充,我在 c.append(b[y]):

之后使用此代码解决了问题
    for y in range(len(b)):
        c.append(b[y])
        with open('Case_File '+today+'.txt', 'a') as Case_File:
            Case_File.write('%s\n'%c)

这有助于将附加值发送到我能够访问并查看我所有案例编号的文件。