How can Python print the value of an attribute but complain it does not exist?

Emre Sevinc emre.sevinc at
Wed Oct 10 21:03:45 CEST 2007


I'm a Python newbie and I'm having a strange trouble with the
following code:
import feedparser
import re

def getwordcounts(url):
    # Parse the feed
    d = feedparser.parse(url)
    wc = {}

    # Loop over all the entries
    for e in d.entries:
        if 'summary' in e: summary = e.summary
        else: summary = e.description

        # Extract a list of words
        words = getwords(e.title + ' ' + summary)
        for word in words:
            wc.setdefault(word, 0)
            wc[word] += 1

    print d.feed.title
    return d.feed.title

def getwords(html):
    # Remove all the HTML tags
    txt = re.compile(r'<[^>]+>').sub('', html)

    # Split words by all non-alpha characters
    words = re.compile(r'[^A-Z^a-z]+').split(txt)

    # Convert to lowercase
    return [word.lower() for word in words if word != '']

apcount = {}
wordcounts = {}
for feedurl in file('feedlist1-2.txt'):
    title = getwordcounts(feedurl)

When I run it:

$ python
Signal vs. Noise
Traceback (most recent call last):
  File "", line 37, in ?
    title = getwordcounts(feedurl)
  File "", line 21, in getwordcounts
    print d.feed.title
  File "/var/lib/python-support/python2.4/", line 236, in
    raise AttributeError, "object has no attribute '%s'" % key
AttributeError: object has no attribute 'title'

The strange thing is that it DOES print the value d.feed.title then
complains AttributeError: object has no attribute 'title'. What am I
doing wrong?

The file feedlist1-2.txt includes just a single line:

$ cat feedlist1-2.txt

I'm using Python 2.4 on Debian GNU/Linux.

Any ideas about how to fix this error message?


Emre Sevinc

More information about the Python-list mailing list