Python Forum
Implementing classes , RSS feed program
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Implementing classes , RSS feed program
#1
Question 
News Feed Program. I need help fixing these errors listed below. My code is completed but I don't know how to approach these errors. If you'd like detailed description of the assignment: https://ocw.mit.edu/courses/electrical-e...11_ps5.pdf
Thank you for any suggestions or help. 
Errors that I'm getting: 
Error:
1) line 121, in __init__ WorldTrigger.__init__(self, word) #inherited with a new parameter NameError: name 'WorldTrigger' is not defined 2) line 130, in __init__ WordTrigger.__init__(self.word) AttributeError: 'PublishedTrigger' object has no attribute 'word' 3) line 142, in evaluate return self.is_word_in(story.get_sumamry()) AttributeError: 'NewsStory' object has no attribute 'get_sumamry' 4) line 185, in evaluate self.phrase in story.get_subject() AttributeError: 'NewsStory' object has no attribute 'get_subject' 5) line 201, in filter_stories if trigger.evaluate(story): line 185, in evaluate self.phrase in story.get_subject() AttributeError: 'NewsStory' object has no attribute 'get_subject'
Code: 
#
#
#
#
import feedparser
import ssl
import string
import time
from project_util import translate_html
from news_gui import Popup

#-----------------------------------------------------------------------
#
# Problem Set 5

#======================
# Code for retrieving and parsing
# Google and Yahoo News feeds
# Do not change this code
#======================

def process(url):
    """
    Fetches news items from the rss url and parses them.
    Returns a list of NewsStory-s.
    """
    if hasattr(ssl, '_create_unverified_context'):
        ssl._create_default_https_context = ssl._create_unverified_context
    feed = feedparser.parse(url)
    entries = feed.entries
    ret =
    for entry in entries:
        guid = entry.guid
        title = translate_html(entry.title)
        published = translate_html(entry.published)
        link = entry.link
        summary = translate_html(entry.summary)
        newsStory = NewsStory(guid, title, published, summary, link)
        ret.append(newsStory)
    return ret

#======================
# Part 1
# Data structure design
#======================

# Problem 1

# TODO: NewsStory

class NewsStory():
    def __init__(self, guid, title, published, summary, link) :
        self.guid = guid
        self.title = title
        self.published = published
        self.summary = summary
        self.link = link

    #methods
    def get_guid(self):
        return self.guid #gives parameter values

    def get_title(self):
        return self.title

    def get_published(self):
        return self.published

    def get_summary(self):
        return self.summary

    def get_link(self):
        return self.link



#======================
# Part 2
# Triggers
#======================

#Superclass
class Trigger(object):
    def evaluate(self, story):
        """
        Returns True if an alert should be generated
        for the given news item, or False otherwise.
        """
        raise NotImplementedError

# Whole Word Triggers
# Problems 2-5

# WordTrigger (sub of trigger)
class WordTrigger(Trigger):
    def __init__(self,word):            #override
        self.word = word

    def is_word_in(self,text):
        word = self.word.lower()
        text = text.lower()

        for punct in string.punctuation:
            text = text.replace(punct, " ")         #replaces all the punctuation with space
        split_text = text.split(" ")                    #splits the text based on spaces

        if word in  split_text:
            return true

        else:
            return false

        #return word in split_text


# TitleTrigger (sub of word trigger)
class TitleTrigger(WordTrigger):
    def __init__(self, word):
        WorldTrigger.__init__(self, word)                #inherited with a new parameter
        #self.word = word                                            #override. same as above

    def evaluate(self, story):
                                                                                              #inherited methods
      return self.is_word_in(story.get_title())
# TODO: PublishedTrigger (sub of word trigger)
class PublishedTrigger(WordTrigger):
    def __init__(self,word):
        WordTrigger.__init__(self.word)

    def evaluate(self, story):
           return self.is_word_in(story.get.published())


# TODO: SummaryTrigger (sub of word trigger)
class SummaryTrigger(WordTrigger):
    def __init__(self, word):
        WordTrigger.__init__(self, word)

    def evaluate(self, story):
        return self.is_word_in(story.get_sumamry())


# Composite Triggers
# Problems 6-8

# TODO: NotTrigger (sub of trigger)
class NotTrigger(Trigger):
    def __init__(self, trigger):
        self.t = trigger

    def evaluate(self,  story):
        return not self.t.evaluate(story)
# TODO: AndTrigger (sub of trigger)
class AndTrigger(Trigger):
    def __init__(self, trigger1, trigger2):
        self.t1 = trigger1
        self.t2 = trigger2

    def evaluate(self, story):
        return self.t1.evaluate(story) and self.t2.evaluate(story)


# TODO: OrTrigger (sub of trigger)
class OrTrigger(Trigger):
    def __init__(self, trigger1, trigger2):
        self.t1 = trigger1
        self.t2 = trigger2

    def evaluate(self, story):
        return self.t1.evaluate(story) or self.t2.evaluate(story)

# Phrase Trigger
# Question 9

# TODO: PhraseTrigger
class PhraseTrigger(Trigger):
    def __init__(self, phrase):
        self.phrase = phrase

    def evaluate(self, story):
        return self.phrase in story.get_title() or \
               self.phrase in story.get_summary() or \
               self.phrase in story.get_subject()

#======================
# Part 3
# Filtering
#======================

def filter_stories(stories, triggerlist):
    """
    Takes in a list of NewsStory-s.
    Returns only those stories for whom
    a trigger in triggerlist fires.
    """
    res =
    for story in stories:
        for trigger in triggerlist:
            if trigger.evaluate(story):
                res.append(story)
                break
    return res

#======================
# Part 4
# User-Specified Triggers
#======================

def readTriggerConfig(filename):
    """
    Returns a list of trigger objects
    that correspond to the rules set
    in the file filename
    """
    # Here's some code that we give you
    # to read in the file and eliminate
    # blank lines and comments
    triggerfile = open(filename, "r")
    all = [ line.rstrip() for line in triggerfile.readlines() ]
    lines =
    for line in all:
        if len(line) == 0 or line[0] == '#':
            continue
        lines.append(line)

    triggers =
    trigger_map = {}
    for line in lines:

        linesplit = line.split(" ")

        # make new trigger
        if linesplit[0] != "ADD":
            trigger = makeTrigger(trigger_map, linesplit[1],
                                  linesplit[2:], linesplit[0])

        #add triggers
        else:
            for name in linesplit[1:]:
                triggers.append(trigger_map[name])

    return triggers

import _thread

def main_thread(p):
    # A sample trigger list - you'll replace
    # this with something more configurable in Problem 11
    t1 = SummaryTrigger("Australia")
    t2 = TitleTrigger("Google")
    t3 = PhraseTrigger("White House")
    t4 = OrTrigger(t2, t3)
    triggerlist = [t1, t4]

    triggerlist = readTriggerConfig("triggers.txt")

    guidShown =

    while True:
        print("Polling...")

        # Get stories from Google's Top Stories RSS news feed
        stories = process("http://news.google.com/news?output=rss")
        # Get stories from Yahoo's Top Stories RSS news feed
        stories.extend(process("http://rss.news.yahoo.com/rss/topstories"))

        # Only select stories we're interested in
        stories = filter_stories(stories, triggerlist)

        # Don't print a story if we have already printed it before
        newstories =
        for story in stories:
            if story.get_guid() not in guidShown:
                newstories.append(story)

        for story in newstories:
            guidShown.append(story.get_guid())
            p.newWindow(story)

        print("Sleeping...")
        time.sleep(SLEEPTIME)

SLEEPTIME = 60 #seconds -- how often we poll
if __name__ == '__main__':
    p = Popup()
    _thread.start_new_thread(main_thread, (p,))
    p.start()

Attached Files

.py   ps5.py (Size: 7.27 KB / Downloads: 576)
Reply
#2
I believe the error is actually related to line 181-183.

I'd first print out story to see if it looks like it is a candidate for logical or,
then try to do the logical or prior to returning a value until the issue is isolated.

It looks OK to me
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need help implementing an input with file operations Gaijin 3 2,060 Jun-08-2022, 05:50 PM
Last Post: Gaijin
  Implementing spam detector code into a GUI nikolassj 2 2,166 Apr-22-2020, 07:49 PM
Last Post: nikolassj
  RSS Feed reader rfrancocantero 4 103,973 Aug-03-2018, 07:31 PM
Last Post: rfrancocantero

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020