-
Notifications
You must be signed in to change notification settings - Fork 1
/
ps7.py
347 lines (277 loc) · 9.65 KB
/
ps7.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# 6.00.1x Problem Set 7
# RSS Feed Filter
import feedparser
import string
import time
from project_util import translate_html
from Tkinter import *
#-----------------------------------------------------------------------
#
# Problem Set 7
#======================
# Code for retrieving and parsing RSS 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.
"""
feed = feedparser.parse(url)
entries = feed.entries
ret = []
for entry in entries:
guid = entry.guid
title = translate_html(entry.title)
link = entry.link
summary = translate_html(entry.summary)
try:
subject = translate_html(entry.tags[0]['term'])
except AttributeError:
subject = ""
newsStory = NewsStory(guid, title, subject, summary, link)
ret.append(newsStory)
return ret
#======================
#======================
# Part 1
# Data structure design
#======================
# Problem 1
# TODO: NewsStory
class NewsStory(object):
def __init__(self, guid, title, subject, summary, link):
self.guid = guid
self.title = title
self.subject = subject
self.summary = summary
self.link = link
def getGuid(self):
return self.guid
def getTitle(self):
return self.title
def getSubject(self):
return self.subject
def getSummary(self):
return self.summary
def getLink(self):
return self.link
#======================
# Part 2
# Triggers
#======================
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
# TODO: WordTrigger
class WordTrigger(Trigger):
def __init__(self, word):
self.word = word
def isWordIn(self, text):
textModified = text[:]
for char in string.punctuation:
textModified = textModified.replace(char, " ")
if self.word.lower() in textModified.lower().split(" "):
return True
return False
# TODO: TitleTrigger
class TitleTrigger(WordTrigger):
def evaluate(self, news):
if self.isWordIn(news.getTitle()):
return True
return False
# TODO: SubjectTrigger
class SubjectTrigger(WordTrigger):
def evaluate(self, news):
if self.isWordIn(news.getSubject()):
return True
return False
# TODO: SummaryTrigger
class SummaryTrigger(WordTrigger):
def evaluate(self, news):
if self.isWordIn(news.getSummary()):
return True
return False
# Composite Triggers
# Problems 6-8
# TODO: NotTrigger
class NotTrigger(Trigger):
def __init__(self, trig):
self.trig = trig
def evaluate(self, news):
if not self.trig.evaluate(news):
return True
return False
# TODO: AndTrigger
class AndTrigger(Trigger):
def __init__(self, firstTrig, secondTrig):
self.firstTrig = firstTrig
self.secondTrig = secondTrig
def evaluate(self, news):
if self.firstTrig.evaluate(news) and self.secondTrig.evaluate(news):
return True
return False
# TODO: OrTrigger
class OrTrigger(Trigger):
def __init__(self, firstTrig, secondTrig):
self.firstTrig = firstTrig
self.secondTrig = secondTrig
def evaluate(self, news):
if self.firstTrig.evaluate(news) or self.secondTrig.evaluate(news):
return True
return False
# Phrase Trigger
# Question 9
# TODO: PhraseTrigger
class PhraseTrigger(Trigger):
def __init__(self, phrase):
self.phrase = phrase
def evaluate(self, news):
if self.phrase in news.getTitle() or self.phrase in news.getSubject() or self.phrase in news.getSummary():
return True
return False
#======================
# Part 3
# Filtering
#======================
def filterStories(stories, triggerlist):
"""
Takes in a list of NewsStory instances.
Returns: a list of only the stories for which a trigger in triggerlist fires.
"""
# TODO: Problem 10
# This is a placeholder (we're just returning all the stories, with no filtering)
temp = list()
for story in stories:
for trigger in triggerlist:
if trigger.evaluate(story):
temp.append(story)
break
return temp
#======================
# Part 4
# User-Specified Triggers
#======================
def makeTrigger(triggerMap, triggerType, params, name):
"""
Takes in a map of names to trigger instance, the type of trigger to make,
and the list of parameters to the constructor, and adds a new trigger
to the trigger map dictionary.
triggerMap: dictionary with names as keys (strings) and triggers as values
triggerType: string indicating the type of trigger to make (ex: "TITLE")
params: list of strings with the inputs to the trigger constructor (ex: ["world"])
name: a string representing the name of the new trigger (ex: "t1")
Modifies triggerMap, adding a new key-value pair for this trigger.
Returns a new instance of a trigger (ex: TitleTrigger, AndTrigger).
"""
# TODO: Problem 11
if triggerType == 'SUBJECT':
triggerMap[name] = SubjectTrigger(params[0])
elif triggerType == 'TITLE':
triggerMap[name] = TitleTrigger(params[0])
elif triggerType == 'SUMMARY':
triggerMap[name] = SummaryTrigger(params[0])
elif triggerType == 'PHRASE':
triggerMap[name] = PhraseTrigger(" ".join(params))
elif triggerType == 'NOT':
triggerMap[name] = NotTrigger(triggerMap[params[0]])
elif triggerType == 'AND':
triggerMap[name] = AndTrigger(triggerMap[params[0]], triggerMap[params[1]])
elif triggerType == 'OR':
triggerMap[name] = OrTrigger(triggerMap[params[0]], triggerMap[params[1]])
return triggerMap[name]
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 = []
triggerMap = {}
# Be sure you understand this code - we've written it for you,
# but it's code you should be able to write yourself
for line in lines:
linesplit = line.split(" ")
# Making a new trigger
if linesplit[0] != "ADD":
trigger = makeTrigger(triggerMap, linesplit[1],
linesplit[2:], linesplit[0])
# Add the triggers to the list
else:
for name in linesplit[1:]:
triggers.append(triggerMap[name])
return triggers
import thread
SLEEPTIME = 60 #seconds -- how often we poll
def main_thread(master):
# A sample trigger list - you'll replace
# this with something more configurable in Problem 11
try:
# These will probably generate a few hits...
t1 = TitleTrigger("Obama")
t2 = SubjectTrigger("Romney")
t3 = PhraseTrigger("Election")
t4 = OrTrigger(t2, t3)
triggerlist = [t1, t4]
# TODO: Problem 11
# After implementing makeTrigger, uncomment the line below:
#triggerlist = readTriggerConfig("triggers.txt")
# **** from here down is about drawing ****
frame = Frame(master)
frame.pack(side=BOTTOM)
scrollbar = Scrollbar(master)
scrollbar.pack(side=RIGHT,fill=Y)
t = "Google & Yahoo Top News"
title = StringVar()
title.set(t)
ttl = Label(master, textvariable=title, font=("Helvetica", 18))
ttl.pack(side=TOP)
cont = Text(master, font=("Helvetica",14), yscrollcommand=scrollbar.set)
cont.pack(side=BOTTOM)
cont.tag_config("title", justify='center')
button = Button(frame, text="Exit", command=root.destroy)
button.pack(side=BOTTOM)
# Gather stories
guidShown = []
def get_cont(newstory):
if newstory.getGuid() not in guidShown:
cont.insert(END, newstory.getTitle()+"\n", "title")
cont.insert(END, "\n---------------------------------------------------------------\n", "title")
cont.insert(END, newstory.getSummary())
cont.insert(END, "\n*********************************************************************\n", "title")
guidShown.append(newstory.getGuid())
while True:
print "Polling . . .",
# Get stories from Google's Top Stories RSS news feed
stories = process("http://news.google.com/?output=rss")
# Get stories from Yahoo's Top Stories RSS news feed
stories.extend(process("http://rss.news.yahoo.com/rss/topstories"))
# Process the stories
stories = filterStories(stories, triggerlist)
map(get_cont, stories)
scrollbar.config(command=cont.yview)
print "Sleeping..."
time.sleep(SLEEPTIME)
except Exception as e:
print e
if __name__ == '__main__':
root = Tk()
root.title("Some RSS parser")
thread.start_new_thread(main_thread, (root,))
root.mainloop()