Python 我在运行MIT 6.0001 F16 pset5 ps5.py时遇到了递归错误

Python 我在运行MIT 6.0001 F16 pset5 ps5.py时遇到了递归错误,python,Python,在完成之前的部分后,我在做麻省理工学院2016年秋季课程6.0001的pset5时。我正在做pset的过滤部分,如下图所示 因此,在运行ps5.py之后,我得到了重复的错误消息: 文件“/Users/eric.ling/Desktop/Introduction to Computer Science and Programming in Python/pset5/mtTkinter.py”,第138行,在__ self.原始初始值(*args,**kwargs) 文件“/Users/eric.

在完成之前的部分后,我在做麻省理工学院2016年秋季课程6.0001的pset5时。我正在做pset的过滤部分,如下图所示

因此,在运行ps5.py之后,我得到了重复的错误消息:

文件“/Users/eric.ling/Desktop/Introduction to Computer Science and Programming in Python/pset5/mtTkinter.py”,第138行,在__ self.原始初始值(*args,**kwargs) 文件“/Users/eric.ling/Desktop/Introduction to Computer Science and Programming in Python/pset5/mtTkinter.py”,第138行,in_-Tk_-init self.\uuuu original\uuuuu init\uuuuu mtTkinter(*args,**kwargs)

递归错误:超过最大递归深度 我不知道我哪里做错了,有人能帮忙吗

# 6.0001/6.00 Problem Set 5 - RSS Feed Filter
# Name:
# Collaborators:
# Time:

import feedparser
import string
import time
import threading
from project_util import translate_html
from mtTkinter import *
from datetime import datetime
import pytz


#-----------------------------------------------------------------------

#======================
# 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.
    """
    feed = feedparser.parse(url)
    entries = feed.entries
    ret = []
    for entry in entries:
        guid = entry.guid
        title = translate_html(entry.title)
        link = entry.link
        description = translate_html(entry.description)
        pubdate = translate_html(entry.published)

        try:
            pubdate = datetime.strptime(pubdate, "%a, %d %b %Y %H:%M:%S %Z")
            pubdate.replace(tzinfo=pytz.timezone("GMT"))
          #  pubdate = pubdate.astimezone(pytz.timezone('EST'))
          #  pubdate.replace(tzinfo=None)
        except ValueError:
            pubdate = datetime.strptime(pubdate, "%a, %d %b %Y %H:%M:%S %z")

        newsStory = NewsStory(guid, title, description, link, pubdate)
        ret.append(newsStory)
    return ret

#======================
# Data structure design
#======================

# Problem 1

# TODO: NewsStory
class NewsStory(object):
    def __init__(self, guid, title, description, link, pubdate):
        self.guid = guid
        self.title = title
        self.description = description
        self.link = link
        self.pubdate = pubdate
    def get_guid(self):
        return self.guid
    def get_title(self):
        return self.title
    def get_description(self):
        return self.description
    def get_link(self):
        return self.link
    def get_pubdate(self):
        return self.pubdate

#======================
# Triggers
#======================

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

# PHRASE TRIGGERS

# Problem 2
# TODO: PhraseTrigger
class PhraseTrigger(Trigger):
    def __init__(self, trigger):
        self.trigger = trigger.lower()
    def is_phrase_in(self, text):
        text = text.lower()
        for mark in string.punctuation:
            text = text.replace(mark, ' ')
        text = ' '.join(text.split())
        if self.trigger in text:
            counter = text.count(self.trigger)
            for n in range(counter):
                loc = text.find(self.trigger)
                if loc == 0:
                    flag1 = 1
                else:
                    if text[loc-1] == ' ':
                        flag1 = 1
                    else:
                        flag1 = 0
                try:
                    if text[loc+len(self.trigger)] == ' ':
                        flag2 = 1
                    else:
                        flag2 = 0
                except IndexError:
                    flag2 = 1
                if flag1 == 1 and flag2 == 1:
                    return True
                else:
                    text = text[len(self.trigger)-1:]


        return False

# Problem 3
# TODO: TitleTrigger
class TitleTrigger(PhraseTrigger):
    def evaluate(self, story):
        return self.is_phrase_in(story.get_title())


# Problem 4
# TODO: DescriptionTrigger
class DescriptionTrigger(PhraseTrigger):
    def evaluate(self, story):
        return self.is_phrase_in(story.get_description())       

# TIME TRIGGERS

# Problem 5
# TODO: TimeTrigger
# Constructor:
#        Input: Time has to be in EST and in the format of "%d %b %Y %H:%M:%S".
#        Convert time from string to a datetime before saving it as an attribute.
class TimeTrigger(Trigger):
    def __init__(self, time_trigger):
        self.utc = pytz.UTC
        self.time_trigger = datetime.strptime(time_trigger, "%d %b %Y %H:%M:%S").replace(tzinfo=self.utc)

# Problem 6
# TODO: BeforeTrigger and AfterTrigger
class BeforeTrigger(TimeTrigger):
    def evaluate(self, story):
        pubdate = story.get_pubdate().replace(tzinfo=self.utc)
        return self.time_trigger > pubdate

class AfterTrigger(TimeTrigger):
    def evaluate(self, story):
        pubdate = story.get_pubdate().replace(tzinfo=self.utc)
        return self.time_trigger < pubdate


# COMPOSITE TRIGGERS

# Problem 7
# TODO: NotTrigger
class NotTrigger(Trigger):
    def __init__(self, trigger_object):
        self.trigger_object = trigger_object
    def evaluate(self, story):
        return not self.trigger_object.evaluate(story)

# Problem 8
# TODO: AndTrigger
class AndTrigger(Trigger):
    def __init__(self, trigger_object1, trigger_object2):
        self.trigger_object1 = trigger_object1
        self.trigger_object2 = trigger_object2
    def evaluate(self, story):
        return self.trigger_object1.evaluate(story) and self.trigger_object2.evaluate(story)


# Problem 9
# TODO: OrTrigger
class OrTrigger(Trigger):
    def __init__(self, trigger_object1, trigger_object2):
        self.trigger_object1 = trigger_object1
        self.trigger_object2 = trigger_object2
    def evaluate(self, story):
        return self.trigger_object1.evaluate(story) or self.trigger_object2.evaluate(story)


#======================
# Filtering
#======================

# Problem 10
def filter_stories(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)
    result = []
    for story in stories:
        for trigger in triggerlist:
            if trigger.evaluate(story):
                result.append(story)
                break
    return result



#======================
# User-Specified Triggers
#======================
# Problem 11
def read_trigger_config(filename):
    """
    filename: the name of a trigger configuration file

    Returns: a list of trigger objects specified by the trigger configuration
        file.
    """
    # We give you the code to read in the file and eliminate blank lines and
    # comments. You don't need to know how it works for now!
    trigger_file = open(filename, 'r')
    lines = []
    for line in trigger_file:
        line = line.rstrip()
        if not (len(line) == 0 or line.startswith('//')):
            lines.append(line)

    # TODO: Problem 11
    # line is the list of lines that you need to parse and for which you need
    # to build triggers

    print(lines) # for now, print it so you see what it contains!



SLEEPTIME = 120 #seconds -- how often we poll

def main_thread(master):
    # A sample trigger list - you might need to change the phrases to correspond
    # to what is currently in the news
    try:
        t1 = TitleTrigger("election")
        t2 = DescriptionTrigger("Trump")
        t3 = DescriptionTrigger("Clinton")
        t4 = AndTrigger(t2, t3)
        triggerlist = [t1, t4]

        # Problem 11
        # TODO: After implementing read_trigger_config, uncomment this line 
        # triggerlist = read_trigger_config('triggers.txt')

        # HELPER CODE - you don't need to understand this!
        # Draws the popup window that displays the filtered stories
        # Retrieves and filters the stories from the RSS feeds
        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)
        guidShown = []
        def get_cont(newstory):
            if newstory.get_guid() not in guidShown:
                cont.insert(END, newstory.get_title()+"\n", "title")
                cont.insert(END, "\n---------------------------------------------------------------\n", "title")
                cont.insert(END, newstory.get_description())
                cont.insert(END, "\n*********************************************************************\n", "title")
                guidShown.append(newstory.get_guid())

        while True:

            print("Polling . . .", end=' ')
            # 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://news.yahoo.com/rss/topstories"))

            stories = filter_stories(stories, triggerlist)

            list(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")
    t = threading.Thread(target=main_thread, args=(root,))
    t.start()
    root.mainloop()
#6.0001/6.00问题集5-RSS源筛选器
#姓名:
#合作者:
#时间:
导入feedparser
导入字符串
导入时间
导入线程
从project\u util导入翻译\u html
从金特进口*
从日期时间导入日期时间
进口皮茨
#-----------------------------------------------------------------------
#======================
#用于检索和解析的代码
#谷歌和雅虎新闻源
#不要更改此代码
#======================
def进程(url):
"""
从rss url获取新闻项目并对其进行解析。
返回NewsStory-s的列表。
"""
feed=feedparser.parse(url)
entries=feed.entries
ret=[]
对于条目中的条目:
guid=entry.guid
title=翻译html(entry.title)
link=entry.link
description=translate\u html(entry.description)
pubdate=translate\u html(entry.published)
尝试:
pubdate=datetime.strtime(pubdate,“%a,%d%b%Y%H:%M:%S%Z”)
pubdate.replace(tzinfo=pytz.timezone(“GMT”))
#pubdate=pubdate.astimezone(pytz.timezone('EST'))
#pubdate.replace(tzinfo=None)
除值错误外:
pubdate=datetime.strtime(pubdate,“%a,%d%b%Y%H:%M:%S%z”)
newsStory=新闻故事(guid、标题、描述、链接、发布日期)
ret.append(新闻故事)
回程网
#======================
#数据结构设计
#======================
#问题1
#待办事项:新闻报道
类NewsStory(对象):
定义初始化(self、guid、标题、描述、链接、发布日期):
self.guid=guid
self.title=标题
self.description=描述
self.link=link
self.pubdate=pubdate
def get_guid(自身):
返回self.guid
def get_标题(自我):
返回自己的标题
def get_说明(自我):
返回自我描述
def get_链接(自):
返回自链接
def获取发布日期(自我):
返回self.publidate
#======================
#触发
#======================
类触发器(对象):
def评估(自我、故事):
"""
如果应生成警报,则返回True
对于给定的新闻项,否则为False。
"""
#不要改变这个!
引发未实现的错误
#短语触发器
#问题2
#TODO:短语触发器
类短语触发器(触发器):
定义初始化(自身,触发器):
self.trigger=trigger.lower()
def是(self,text)中的短语:
text=text.lower()
对于字符串中的标记。标点符号:
text=text.replace(标记“”)
text=''.join(text.split())
如果文本中为self.trigger:
计数器=text.count(self.trigger)
对于范围内的n(计数器):
loc=text.find(self.trigger)
如果loc==0:
flag1=1
其他:
如果文本[loc-1]='':
flag1=1
其他:
flag1=0
尝试:
如果文本[loc+len(自触发)]='':
flag2=1
其他:
flag2=0
除索引器外:
flag2=1
如果flag1==1和flag2==1:
返回真值
其他:
text=text[len(self.trigger)-1:]
返回错误
#问题3
#待办事项:TitleTrigger
类别标题触发器(短语触发器):
def评估(自我、故事):
返回self.is_短语_in(story.get_title())
#问题4
#TODO:描述触发器
类描述符触发器(短语触发器):
def评估(自我、故事):
返回self.is_短语_in(story.get_description())
#时间触发器
#问题5
#TODO:时间触发器
#建造商:
#输入:时间必须为EST格式,格式为“%d%b%Y%H:%M:%S”。
#将时间从字符串转换为日期时间,然后将其保存为属性。
类时间触发器(触发器):
def uuu init uuuu(自身、时间触发):
self.utc=pytz.utc
self.time\u trigger=datetime.strtime(time\u trigger,“%d%b%Y%H:%M:%S”)。替换(tzinfo=self.utc)
#问题6
#TODO:触发前和触发后
类BeforeTrigger(TimeTrigger):
def评估(自我、故事):
pubdate=story.get_pubdate().replace(tzinfo=self.utc)
返回self.time\u trigger>pubdate
类后触发器(时间触发器):
def评估(自我、故事):
pubdate=story.get_pubdate().replace(tzinfo=self.utc)
返回self.time\u触发器