为什么我的代码没有编译
Why is my code not compiling
我正在学习 Python 并决定编写一个非常简单的 Python 机器人来在 Reddit 上回复。
编译时出现以下错误:
File "C:\Python35\Scripts\RedditBot\Reddit.py", line 28
except attributeerror:
^ SyntaxError: invalid syntax
我看不出是什么原因造成的,因为代码对我来说是正确的。
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()
您有两个问题。
- traceback中显示的第一个是缩进。 "try"
和 "except" 必须处于同一缩进级别。
- 第二个是对属性错误的引用。它需要像 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
我正在学习 Python 并决定编写一个非常简单的 Python 机器人来在 Reddit 上回复。
编译时出现以下错误:
File "C:\Python35\Scripts\RedditBot\Reddit.py", line 28 except attributeerror: ^ SyntaxError: invalid syntax
我看不出是什么原因造成的,因为代码对我来说是正确的。
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()
您有两个问题。
- traceback中显示的第一个是缩进。 "try" 和 "except" 必须处于同一缩进级别。
- 第二个是对属性错误的引用。它需要像 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