Я работаю над кодом, который должен быть поисковой системой для символов marvel, однако мой раздел, посвященный питону, возвращает ошибку 500, когда она вызывается JavaScript. Я знаю, что javascript работает, потому что я тестировал его, используя образец скрипта на python, который дал нам профессор, но я не знаю, почему мой код не работает. Предполагается вернуть строку с запятыми, разделяющими различные значения (имя персонажа и ссылку на его вики). Код работает, когда я изменяю cgi.FieldStorage () на простой ввод и просто запускаю его сам, поэтому я не уверен, что происходит не так.
#!/usr/bin/env python3
# namelookup.py - Program to display name statistics
#!/usr/bin/env python
import cgi;
import cgitb
cgitb.enable()
from sortedcontainers import SortedDict
filePath="/home/class/SoftDev/namedata/"
def readfile(filename):
infile=open(filename,mode='r')
array=[]
for line in infile:
templine=line
array.append(templine.split(','))
infile.close()
return array[::-1]
def removePunctuation(s):
#Remove all punctuation from a string
import string
for c in string.punctuation:
s= s.replace(c,"")
return s
def createNameIndex(array):
#creates an index of every name and the number of the lines tha have that number on it
index={}
arraylen=len(array)
for x in range(arraylen):
allnames=removePunctuation(array[x][1]).lower().split(' ')
#catalogs each name, so "Peter Parker" will also appear wheyou search for just Peter or Parker. This has an addebenefit in that it allows the program to determine answermore relevant to the search, see the sortrelevancy function
for name in allnames:
if not name in index:
index[name]=[x]
else:
index[name].append(x)
return index
def createYearIndex(array):
#creates an index the same as the name index, except with years instead of names
index={}
arraylen=len(array)
for x in range(arraylen):
year=array[x][12][0:4]
if year in index:
index[year].append(x)
else:
index[year]=[x]
return index
def searchFor(term,nameindex,yearindex):
#searches the indexes for the desired term, keeping track oeach row that comes back, including duplicates, which wilbe used by sortRelevancy
allterms=term.split()
allterms.append(term)
allterms.append(term.replace(" ",''))
results=[]
for word in allterms:
if word in nameindex:
for number in nameindex[word]:
results.append(number)
if word in yearindex:
for number in yearindex[word]:
results.append(number)
return results
def print_header():
print ("""Content-type: text/html\n""")
def sortRelevancy(numberlist):
#counts the number of times that each answer has appeared, then sorts them in that order so that the name that appeared thmost times is at the top.
sortednumbers={}
for number in numberlist:
if not number in sortednumbers:
sortednumbers[number]=1
else:
sortednumbers[number]=sortednumbers[number]+1
finallist=sorted(sortednumbers.items(), key=lambda kv:(kv[1], [0]) )
finallist= finallist[::-1]
return finallist[0:10] # to prevent too many results, only th10 most relevant are shown
def main():
#main function, combines all the above part and supplies the interface for the user
filename=readfile ('/home/class/SoftDev/marvel/marvel-wikia-data.csv')
marvelindex=createNameIndex(filename)
yearindex=createYearIndex(filename)
form = cgi.FieldStorage()
searchforme=removePunctuation(form.getvalue("name").lower())
resultlist=searchFor(searchforme,marvelindex,yearindex)
listicle=sortRelevancy(resultlist)
results=""
print_header()
if listicle==[]:
print("No results found.")
else:
for x in listicle:
results+=filename[x[0]][1]+", "+filename[x[0]][2]+", "
print(results)
main()