如何将 PRAW 排序参数作为函数参数?
How do I place a PRAW sort parameter as a function argument?
我想对各种 subreddits 进行情绪分析,并同时考虑“新”和“热门”提交。我可以通过以下方式做到这一点:
# What I have
def new_submissions(sub):
subreddit = reddit.subreddit(sub).new(limit=100)
for submission in subreddit:
# Do stuff
return new_stuff
def hot_submissions(sub):
subreddit = reddit.subreddit(sub).hot(limit=100)
for submission in subreddit:
# Do stuff
return hot_stuff
new_submissions("subname")
hot_submissions("subname")
在这里,“做事”涉及 40 行相同的代码。我想引用 subreddits 的“排序依据”参数(例如,.new()、.hot())作为函数参数,如下所示:
# What I want
def submissions(sub, sortby):
subreddit = reddit.subreddit(sub).sortby(limit=100)
for submission in subreddit:
# Do stuff
return stuff
submissions("subname", new)
submissions("subname", hot)
我没有成功地让它工作。我该如何处理?
你能做的是
def submissions(subreddit):
for submission in subreddit:
# Do stuff
return stuff
submissions(reddit.subreddit("subname").new(limit=100))
submissions(reddit.subreddit("subname").hot(limit=100))
或者如果您想按照您的要求去做,您可以这样做:
def submissions(sub, sortby):
method_to_call = getattr(reddit.subreddit(sub), sortby)
subreddit = method_to_call(limit=100)
for submission in subreddit:
# Do stuff
return stuff
# new and hot are strings to search for as attributes of the class
submissions("funnyvideos", 'new')
submissions("funnyvideos", 'hot')
我想对各种 subreddits 进行情绪分析,并同时考虑“新”和“热门”提交。我可以通过以下方式做到这一点:
# What I have
def new_submissions(sub):
subreddit = reddit.subreddit(sub).new(limit=100)
for submission in subreddit:
# Do stuff
return new_stuff
def hot_submissions(sub):
subreddit = reddit.subreddit(sub).hot(limit=100)
for submission in subreddit:
# Do stuff
return hot_stuff
new_submissions("subname")
hot_submissions("subname")
在这里,“做事”涉及 40 行相同的代码。我想引用 subreddits 的“排序依据”参数(例如,.new()、.hot())作为函数参数,如下所示:
# What I want
def submissions(sub, sortby):
subreddit = reddit.subreddit(sub).sortby(limit=100)
for submission in subreddit:
# Do stuff
return stuff
submissions("subname", new)
submissions("subname", hot)
我没有成功地让它工作。我该如何处理?
你能做的是
def submissions(subreddit):
for submission in subreddit:
# Do stuff
return stuff
submissions(reddit.subreddit("subname").new(limit=100))
submissions(reddit.subreddit("subname").hot(limit=100))
或者如果您想按照您的要求去做,您可以这样做:
def submissions(sub, sortby):
method_to_call = getattr(reddit.subreddit(sub), sortby)
subreddit = method_to_call(limit=100)
for submission in subreddit:
# Do stuff
return stuff
# new and hot are strings to search for as attributes of the class
submissions("funnyvideos", 'new')
submissions("funnyvideos", 'hot')