为什么我的代码没有编译

时间:2016-10-21 07:25:56

标签: python praw

我只是在学习Python,并决定编写一个非常简单的Python机器人来回复Reddit。

编译时我收到以下错误:

  

文件" C:\ Python35 \ Scripts \ RedditBot \ Reddit.py",第28行       除了attributeerror:            ^ SyntaxError:语法无效

我无法看到导致这种情况的原因,因为代码对我来说是正确的。

import praw

USERAGENT = "BOT Name"
USERNAME = "Username"
PASSWORD = "Password"
SUBREDDIT = "Subreddit"
MAXPOSTS = 100

SETPHRASES = ["Phrase", "PhraseOne"]
SETRESPONSE = "This is the response."

print('Logging in to Reddit')
r = praw.Reddit(USERAGENT)
r.login (USERNAME, PASSWORD)

def replybot():
    print('Fetching Subreddit ' + SUBREDDIT)
    subreddit = r.get_subreddit(SUBREDDIT)
    print('Fetching comments')
    comments = subreddit.get_comments(limit=MAXPOSTS)
    for comment in comments:
        try:
            cauthor = comment.author.name
            cbody = comment.body.lower()
            if any(key.lower() in cbody for key in SETPHRASES):
                print("Replying to " + cauthor)
                comment.reply(SETRESPONSE)
            except attributeerror:
                pass
replybot()

1 个答案:

答案 0 :(得分:3)

你有两个问题。

  • 第一个显示在回溯中的是缩进。 "尝试" 和"除了"必须在同一级别的缩进。
  • 第二个是对attributeerror的引用。需要像在AttributeError中那样进行传播。

因此,for循环的内部应如下所示:

try:
   cauthor = comment.author.name
   cbody = comment.body.lower()
   if any(key.lower() in cbody for key in SETPHRASES):
      print("Replying to " + cauthor)
      comment.reply(SETRESPONSE)
except AttributeError:
   pass