gpt4 book ai didi

python - 在 Python 中为 Bing API 处理 JSON 响应

转载 作者:太空宇宙 更新时间:2023-11-04 06:29:13 28 4
gpt4 key购买 nike

我正在使用 Bing API(这里的 python 绑定(bind):http://uswaretech.com/blog/2009/06/bing-python-api/)用 python 编写答案聚合器站点的后端。以下是我的代码:

#!/usr/bin/python
from bingapi import bingapi
import re
import cgi
import cgitb
from HTMLParser import HTMLParser

class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)

def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()

def strip_tags2(data):
p = re.compile(r'<[^<]*?>')
q = re.compile(r'[&;!@#$%^*()]*')
data = p.sub('', data)
return q.sub('', data)

def getUrl(item):
return item['Url']

def getContent(item):
return item['Description']

def getInfo(siteStr, qry):
query = "{0} {1}".format(qry, siteStr)
bing = bingapi.Bing('APP_ID_HERE')
j = bing.do_web_search(query)
results = j['SearchResponse']['Web']['Results']
return result

def updateRecent(qry):
f = open("recent.txt", "r")
lines = f.readlines()
f.close()
lines = lines[1:]

if len(qry) > 50: #truncate if string too long
qry = (qry[:50] + '...')
qry = strip_tags2(qry) #strip out the html if injection try

lines.append("\n%s" % qry)
f = open("recent.txt", "w")
f.writelines(lines)
f.close()

if __name__ == '__main__':
form = cgi.FieldStorage()
qry = form["qry"].value
qry = r'%s' % qry

updateRecent(qry)

siteStr = "site:answers.yahoo.com OR site:chacha.com OR site:blurtit.com OR site:answers.com OR site:question.com OR site:answerbag.com OR site:stackexchange.com"

print "Content-type: text/html"
print

header = open("header.html", "r")
contents = header.readlines()
header.close()
for item in contents:
print item

print """
<div id="results">
<center><h1>Results:</h1></center>
"""
print getInfo(siteStr, qry)
for item in getInfo(siteStr, qry):
print "<h3>%s</h3>" % getUrl(item)
print "<br />"
print "<p style=\"color:gray\">%s</p>" % getContent(item)
print "<br />"
print "</div>"

footer = open("footer.html", "r")
contents = footer.readlines()
footer.close()
for thing in contents:
print thing

出于某种原因,当我在浏览器中运行它(使用文本输入向它发送查询)时,它没有打印任何内容。有人可以解释为什么会这样吗?提前致谢!

最佳答案

没关系,只是发现了一个语法错误,我猜是 apache 没有发现。在“getInfo()”函数中,它在应该说“返回结果”时说“返回结果”。

关于python - 在 Python 中为 Bing API 处理 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4911735/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com