갈루아의 반서재

def getwordcounts(url):
    d=feedparser.parse(url)
    wc={}
   
    for e in d.entries:
        if 'summary' in e: summary=e.summary
        else: summary=e.description
       
        words=getwords(e.title+' '+summary)
        for word in words:
            wc.setdefault(word,0)
            wc[word]+=1
   
    return d.feed.title, wc 


파싱하고자 하는 URL이 유효한 피드가 아닌 경우, 예를 들어 URL 이 일반 웹페이지거나 피드가 없는 경우 아래와 같은 에러를 일으킨다.


AttributeError at

object has no attribute 'title'


이 경우 getattr 을 이용하면 title이 없는 경우에도 에러 페이지를 출력하지 않고 처리가 가능하다.


def getwordcounts(url):
    d=feedparser.parse(url)
    wc={}
   
    for e in d.entries:
        if 'summary' in e: summary=e.summary
        else: summary=e.description
       
        words=getwords(e.title+' '+summary)
        for word in words:
            wc.setdefault(word,0)
            wc[word]+=1
   
    return getattr(d.feed, 'title', 'Unknown title'), wc 


아래 페이지 참조.


getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

https://docs.python.org/2/library/functions.html