我正在用Python编写一个脚本,该脚本提示您提出问题,并分析AskReddit的subreddit并给您答复。我的代码是:
import requests
import json
import random
#The main function that will grab a reply
def grab_reply(question):
#Navigate to the Search Reddit Url
r = requests.get('https://www.reddit.com/r/AskReddit/search.json?q=' + question + '&sort=relevance&t=all', headers = {'User-agent': 'Chrome'})
answers = json.loads(r.text) #Load the JSON file
Children = answers["data"]["children"]
ans_list= []
for post in Children:
if post["data"]["num_comments"] >= 5: #Greater then 5 or equal comments
ans_list.append (post["data"]["url"])
#If no results are found return "I have no idea"
if len(ans_list) == 0:
return "I have no idea"
#Pick A Random Post
comment_url=ans_list[random.randint(0,len(ans_list)-1)] + '.json?sort=top' #Grab Random Comment Url and Append .json to end
#Navigate to the Comments
r = requests.get(comment_url, headers = {'User-agent': 'Chrome'})
reply= json.loads(r.text)
Children = reply[1]['data']['children']
reply_list= []
for post in Children:
reply_list.append(post["data"]["body"]) #Add Comments to the List
if len(reply_list) == 0:
return "I have no clue"
#Return a Random Comment
return reply_list[random.randint(0,len(reply_list)-1)]
#Main Loop, Always ask for a question
while 1:
input("Ask me anything: ")
q=q.replace(" ", "+") #Replace Spaces with + for URL encoding
print(grab_reply(q)) #Grab and Print the Reply
在终端中运行脚本后,得到以下响应:
NameError: name 'q' is not defined
我已经设法从脚本中消除了大多数错误,但这使我发疯。帮助我,堆栈溢出。
答案 0 :(得分:1)
这可能会帮助
while True:
q = input("Ask me anything: ")
答案 1 :(得分:0)
input("Ask me anything: ")
应为:
q = input("Ask me anything: ")
因此,您没有将输入的结果分配给任何变量。 q
未定义。
答案 2 :(得分:0)
q尚未定义。您应该在使用q之前定义它。