简体   繁体   English

AttributeError: 'AttributeError' object 没有属性 'To'

[英]AttributeError: 'AttributeError' object has no attribute 'To'

I am trying to explore the enron email dataset using python Jupyter notebook.我正在尝试使用 python Jupyter 笔记本探索 enron email 数据集。 But I am getting this attribute error.但我收到此属性错误。 I am trying to read the emails and convert them into csv format so that I can further apply Ml for sentiment analysis.我正在尝试阅读电子邮件并将其转换为 csv 格式,以便我可以进一步应用 Ml 进行情感分析。 import tarfile import re from datetime import datetime from collections import namedtuple, Counter import pandas as pd import altair as alt import tarfile import re from datetime import datetime from collections import namedtuple, Counter import pandas as pd import altair as alt

tar =tarfile.open(r"C:\Users\nikip\Documents\2021\Interview Preparation\sentiment analysis\enron_mail_20150507.tar.gz", "r")
items = tar.getmembers()
Email = namedtuple('Email', 'Date, From, To, Subject, Cc, Bcc, Message')

def get_msg(item_number):
    f = tar.extractfile(items[item_number])
    try:
        date = from_ = to = subject = cc= bcc = message= ''
        in_to = False
        in_message = False
        to = []
        message = []
        item = f.read().decode()
        item = item.replace('\r', '').replace('\t', '')
        lines = item.split('\n')
        
        for num, line in enumerate(lines):
            if line.startswith('Date:') and not date:
                date = datetime.strptime(' '.join(line.split('Date: ')[1].split()[:-2]), '%a, %d %b %Y %H:%M:%S')
            elif line.startswith('From:') and not from_:
                from_ = line.replace('From:', '').strip()                
            elif line.startswith('To:')and not to:
                in_to = True
                to = line.replace('To:', '').replace(',', '').replace(',', '').split()                
            elif line.startswith('Subject:') and not subject:
                in_to = False
                subject = line.replace('Subject:', '').strip()                
            elif line.startswith('Cc:') and not cc:
                cc = line.replace('Cc:', '').replace(',', '').replace(',', '').split()                
            elif line.startswith('Bcc:') and not bcc:
                bcc = line.replace('Bcc:', '').replace(',', '').replace(',', '').split()                
            elif in_to:
                to.extend(line.replace(',', '').split())                
            elif line.statswith('Subject:') and not subject:
                in_to =False                
            elif line.startswith('X-FileName'):
                in_message = True                
            elif in_message:
                message.append(line)
        
        to = '; '.join(to).strip()
        cc = '; '.join(cc).strip()
        bcc = '; '.join(bcc).strip()
        message = ' '.join(message).strip()
        email = Email(date, from_, to, subject, cc, bcc, message)
        return email
    
    except Exception as e:
        return e

msg = get_msg(3002)
msg.date

I am getting error message like below:我收到如下错误消息:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-e1439579a8e7> in <module>
----> 1 msg.To

AttributeError: 'AttributeError' object has no attribute 'To'

Can someone help?thanks in advance有人可以帮忙吗?提前致谢

The problem is that you are return an exception in your get_msg function, which broadly looks like this:问题是您在get_msg function 中返回异常,大致如下所示:

def get_msg(item_number):
  try:
    ...do some stuff...
  except Exception as e:
    return e

It looks like you're triggering an AttributeError exception somewhere in your code, and you're returning that exception, rather than an Email object.看起来您在代码中的某处触发了AttributeError异常,并且返回了该异常,而不是Email object。

You almost never want to have an except statement that suppresses all exceptions like that, because it will hide errors in your code (as we see here).你几乎不想有一个except语句来抑制所有异常,因为它会隐藏你代码中的错误(正如我们在这里看到的)。 It is generally better practice to catch specific exceptions, or at least log the error if your code will continue despite the exception.通常更好的做法是捕获特定的异常,或者至少记录错误,如果你的代码将继续执行,尽管有异常。

As a first step, I would suggest removing the entire try/except block and get your code working without it.作为第一步,我建议删除整个try/except块并让您的代码在没有它的情况下工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM