类似于python中的GoogleSuggest的脚本
我正在写一个类似谷歌建议的脚本。问题是,我正试图得到一个关于下两个最有可能的词的建议。 该示例使用了一个txt文件,该文件工作于_bee.txt。当我写一篇文章“mis”时,我应该得到一些建议,比如“玛丽小姐,泰勒小姐,…”。我只得到“小姐,…”。我怀疑Ajax responseText方法只给出了一个单词? 你知道怎么了吗类似于python中的GoogleSuggest的脚本,python,ajax,Python,Ajax,我正在写一个类似谷歌建议的脚本。问题是,我正试图得到一个关于下两个最有可能的词的建议。 该示例使用了一个txt文件,该文件工作于_bee.txt。当我写一篇文章“mis”时,我应该得到一些建议,比如“玛丽小姐,泰勒小姐,…”。我只得到“小姐,…”。我怀疑Ajax responseText方法只给出了一个单词? 你知道怎么了吗 #看起来像谷歌建议的东西 def count_words(xFile): frequency = {} words=[] for l in ope
#看起来像谷歌建议的东西
def count_words(xFile):
frequency = {}
words=[]
for l in open(xFile, "rt"):
l = l.strip().lower()
for r in [',', '.', "'", '"', "!", "?", ":", ";"]:
l = l.replace(r, " ")
words += l.split()
for i in range(len(words)-1):
frequency[words[i]+" "+words[i+1]] = frequency.get(words[i]+" "+words[i+1], 0) + 1
return frequency
# read valid words from file
ws = count_words("c:/mod_python/working_bee.txt").keys()
def index(req):
req.content_type = "text/html"
return '''
<script>
function complete(q) {
var xhr, ws, e
e = document.getElementById("suggestions")
if (q.length == 0) {
e.innerHTML = ''
return
}
xhr = XMLHttpRequest()
xhr.open('GET', 'suggest_from_file.py/complete?q=' + q, true)
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
ws = eval(xhr.responseText)
e.innerHTML = ""
for (i = 0; i < ws.length; i++)
e.innerHTML += ws[i] + "<br>"
}
}
xhr.send(null)
}
</script>
<input type="text" onkeyup="complete(this.value)">
<div id="suggestions"></div>
'''
def complete(req, q):
req.content_type = "text"
return [w for w in ws if w.startswith(q)]
看看你的代码,我相信你没有向Apache发送正确的东西。您正在向apache发送一个列表,apache需要一个字符串。我建议将您的返回更改为json:
import json
def complete(req, q):
req.content_type = "text"
return json.dumps([w for w in ws if w.startswith(q)])
我建议你把你想完成的步骤一个一个地写出来,然后单独完成,而不是作为一个整体来完成。它可以让你找出你在哪里犯的错误。同时,我将很乐意尝试并帮助您完成这项工作。您使用什么服务器来运行索引和完成功能?如果没有这一点,就很难理解会出什么问题。我使用的是Apache2.2。我一步一步地检查了代码,我怀疑服务器只返回onreadystatechange函数中的第一个单词。Python函数给出了正确的结果。谢谢您,但是我正在使用Python 2.5并尝试安装simplejson,但是遇到了问题。它似乎安装正常,但当我尝试导入时,出现错误“没有名为simplejson的模块”。你知道如何安装吗?你在什么系统上?你打算如何安装?安装python库有很多方法。我最喜欢的一个是。另一个是大多数库附带的基本setup.py脚本。最后是下载源代码并将源文件夹(在本例中为simplejson的项目名称)解压缩/解压到运行脚本的文件夹中。我成功地做到了这一点(您描述的最后一个选项)。现在我在运行脚本时在浏览器(FireFox)中遇到错误。。。ImportError:没有名为simplejson的模块。Json在python中工作正常。我只有Pythin 2.5。我将尝试轻松安装。
import json
def complete(req, q):
req.content_type = "text"
return json.dumps([w for w in ws if w.startswith(q)])