python - Passing string over urls django -
i'm having trouble in understanding error in code, first let me try , explain happening , i'm trying do.
my code designed load 45 separate text files array, including weight of each word/phrase , word phrase itself. has occur @ beginning, before description received.
second, once description received, parsed software words/phrases, compared words/phrases in array.
third, software provides top 3 classes, in rank order (first/second/third) number, along score each class.
i've made django application serve code, have form provide 2 parameters classes , description, this:
class trademarkclassifierform(forms.form): """ todo: forms cover questions initial classifier program :returns: todo """ classes = forms.charfield(max_length=10, label="test trademark classes? type 'yes' or else enter class tested ") description = forms.charfield(widget=forms.textarea) def __init__(self, *args, **kwargs): super(trademarkclassifierform, self).__init__(*args, **kwargs) self.helper = formhelper() self.helper.add_input(submit('submit', 'submit'))
then want pass 2 parameters in view
on url
this:
class trademarkclassifierresultview(formview): """ todo: post should redirect it's on page get, specify set values in query parameters, ?classes=yes&name=nameoftrademarkclass should visible on results page. :param: classes :param: description :returns: todo - params """ template_name = 'trademark.html' form_class = trademarkclassifierform def get(self, request, *args, **kwargs): classes = str(self.request.get.get('classes')) description = str(self.request.get.get('description')) form = trademarkclassifierform(initial={'classes': classes, 'description': description}) context_data = self.get_context_data(classes, description, form=form) return self.render_to_response(context_data) def form_valid(self, form): classes = form.cleaned_data['classes'] description = form.cleaned_data['description'] return redirect(self.get_success_url(classes, description)) def form_invalid(self, form): messages.add_message(self.request, messages.error, "invalid data. please check fields.") return self.render_to_response( self.get_context_data(form=form) ) def get_success_url(self, classes=none, description=none): return reverse("classifier:trademark") + "?classes=" + str(classes) + "&description" + str(description) def get_context_data(self, classes, description, **kwargs): context = super(trademarkclassifierresultview, self).get_context_data(**kwargs) context['classes'] = classes context['description'] = description context['trademark'] = classifymarkbased.control_program(classes, description) return context
now problem error:
environment: request method: request url: http://127.0.0.1:8000/trademark/ django version: 1.11.2 python version: 2.7.12 installed applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'classifier', 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'widget_tweaks', 'debug_toolbar'] installed middleware: ['django.middleware.security.securitymiddleware', 'django.contrib.sessions.middleware.sessionmiddleware', 'django.middleware.common.commonmiddleware', 'django.middleware.csrf.csrfviewmiddleware', 'django.contrib.auth.middleware.authenticationmiddleware', 'django.contrib.messages.middleware.messagemiddleware', 'django.middleware.clickjacking.xframeoptionsmiddleware', 'debug_toolbar.middleware.debugtoolbarmiddleware'] traceback: file "/home/petar/.virtualenvs/trademark/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) file "/home/petar/.virtualenvs/trademark/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) file "/home/petar/.virtualenvs/trademark/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) file "/home/petar/.virtualenvs/trademark/local/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) file "/home/petar/.virtualenvs/trademark/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) file "/home/petar/documents/synergy/trademark/tm_base/classifier/views.py" in 60. context_data = self.get_context_data(classes, description, form=form) file "/home/petar/documents/synergy/trademark/tm_base/classifier/views.py" in get_context_data 82. context['trademark'] = classifymarkbased.control_program(classes, description) file "/home/petar/documents/synergy/trademark/tm_base/classifier/services/classify_mark_based.py" in control_program 89. n = len(word_count_array_for_all_classes[i]) exception type: indexerror @ /trademark/ exception value: list index out of range
this url: url(r'^trademark/', trademarkclassifierresultview.as_view(), name="trademark"),
and part of code should calculate trademark on 2 parameters:
import os import numpy np import re import requests class trademarkservice(object): # coding: utf-8 # in[5]: # compare input string class # words not found,look in dictionary - add text files trademark words # in[6]: # open each trademark class file , read words/frequency array @staticmethod def open_file_read_words(file_name): unique_words_and_count_not_format = [] tm_word_count_array = [] my_list = [] all_possible_entries = 1 open(file_name) f: lines = [line.strip() line in open(file_name)] all_possible_entries = len(lines) tm_word_count_array = [[0 x in range(2)] y in range(all_possible_entries)] = 0 while < all_possible_entries: tm_word_count_array[i] = lines[i].split(',', 1) += 1 = 0 while < all_possible_entries: tm_word_count_array[i][0] = int(tm_word_count_array[i][0]) += 1 return tm_word_count_array # in[7]: # section normalizes word frequency number of words x 1000 @staticmethod def normalize_array(tm_word_count_array): list_of_freqs = [] max_entries = len(tm_word_count_array) list_of_freqs = [0 y in range(max_entries)] = 0 while < max_entries: list_of_freqs[i] = tm_word_count_array[i][0] += 1 max_value = max(list_of_freqs) = 0 while < max_entries: tm_word_count_array[i][0] = ((float(tm_word_count_array[i][0])) / max_entries) * 1000 += 1 return tm_word_count_array # in[8]: # include list of not useful words here @staticmethod def find_not_useful_words(word): not_useful_words = ( "about", "are", "upon", "-", " ", "up", "other", "or", "not", "namely", "more", "made", "in", "for", "except", "but", "being", "all", "against", "was", "were", "will", "that", "its", "on", "it", "at", "was", "our", "your", "ours", "yours", "their", "them", "other", "out", "having", "have", "has", "in", "be", "than", "use", "uses", "using", "", "by", "and", "an", "a", "use", "used", "using", "for", "to", "of", "-)", "-]", "with", "as", "in", "the", "from") test_word in not_useful_words: if word == test_word: return false return true # in[9]: # clean phrases removing problematic characters @staticmethod def clean_up_phrases(data): important_words = '' word = data c in word: if 0 <= ord(c) <= 127: # ascii character. not_a_variable = 0 else: if ord(c) == 201: word = word.replace(c, "e") elif ord(c) == 241: word = word.replace(c, "n") elif ord(c) == 225: word = word.replace(c, "a") elif ord(c) == 251: word = word.replace(c, "u") elif ord(c) == 8206: word = word.replace(c, "") else: word = word.replace(c, "") # continue_yes=raw_input("do want continue?") word = word.lower() word = str(filter(lambda ch: ch not in "?.!/;:,'()[]", word)) # calls function above remove words found interfere classification if data.find_not_useful_words(word): if len(word) > 1: important_words += word return important_words # in[10]: # find important words in string @staticmethod def find_important_words(data): all_entries = len(data) important_words = [] word in data.split(): c in word: if 0 <= ord(c) <= 127: # ascii character. not_a_variable = 0 else: if ord(c) == 201: word = word.replace(c, "e") elif ord(c) == 241: word = word.replace(c, "n") elif ord(c) == 225: word = word.replace(c, "a") elif ord(c) == 251: word = word.replace(c, "u") elif ord(c) == 8206: word = word.replace(c, "") else: word = word.replace(c, "") word = word.lower() word = str(filter(lambda ch: ch not in " ?.!/;:,'()[]", word)) if word.endswith("-"): word = word[:-1] if word.startswith("-"): word = word[:1] if data.find_not_useful_words(word): if len(word) > 1: important_words.append(word) return important_words # in[11]: @staticmethod def analyze_each_line_test_data(test_sentence, n, normalized_tm_word_count_array): # remove problematic characters , words, plus find important words/phrases test_important_phrases = test_sentence.clean_up_phrases(test_sentence) = 0 total_found = 0 total_tm_class_count = 0 total_tm_words_matched = [] # score trademark phrases in string while < n: count_phrases = 0 if len(normalized_tm_word_count_array[i][1].split()) > 1: if test_important_phrases.find(normalized_tm_word_count_array[i][1]) > -1: total_tm_words_matched.append(normalized_tm_word_count_array[i][1]) total_tm_class_count += (normalized_tm_word_count_array[i][0]) total_found += 1 += 1 # decompose string , remove extraneous words, score words in string test_important_words = test_sentence.find_important_words(test_sentence) = 0 while < n: count_words = 0 if test_important_words.count(normalized_tm_word_count_array[i][1]) > 0: total_tm_words_matched.append(normalized_tm_word_count_array[i][1]) count_words = test_important_words.count(normalized_tm_word_count_array[i][1]) total_tm_class_count += (normalized_tm_word_count_array[i][0] * count_words) total_found += 1 += 1 = 0 normalized_tm_word_count_values = [0 y in range(n)] normalized_tm_word_count_words = ['a' y in range(n)] while < n: normalized_tm_word_count_values[i] = normalized_tm_word_count_array[i][0] normalized_tm_word_count_words[i] = normalized_tm_word_count_array[i][1] += 1 total_words_to_match = len(test_important_words) + len(test_important_phrases) not_found_words = list(set(test_important_words) - set(normalized_tm_word_count_words)) return total_found, total_tm_words_matched, not_found_words, total_tm_class_count # in[12]: @staticmethod def open_class_file_read_words_to_array(file_name, file_name_class=none): tm_word_count_array = [] tm_word_count_array = file_name.open_file_read_words(file_name_class) return tm_word_count_array # in[13]: # create file trademark results @staticmethod def create_results_file(file_name, results_array, description): unique_words_and_count_not_format = [] unique_words_and_count_to_write = [] open_file_name = open(file_name, 'a') open_file_name.write("new trademark comparison") open_file_name.write("\n") open_file_name.write(description) open_file_name.write("\n") unique_words_and_count_to_write = np.array(results_array, dtype=object) np.savetxt(open_file_name, unique_words_and_count_to_write, fmt='%s', delimiter=',') open_file_name.write("\n") open_file_name.write("\n") open_file_name.write("\n") open_file_name.close() # in[14]: # section controls program @staticmethod def control_the_program(classes, description): description = [] word_count_array_for_all_classes = [] correct_class_set = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45'] # depending on answer, 1 class worth of trademark words loaded or else loaded # test_all_classes = raw_input( # "test trademark classes? type 'yes' or else enter class tested ") test_all_classes = classes # test description of goods/services # test_data_array = raw_input("provide description of goods or services ") test_data_array = description # file_name_data = raw_input("provide identifier results file ") # file has output of classification engine, including top 3 results # file_name_results = 'user_test_comparison_results_' + file_name_data + '.txt' # call program open each file of trademark words in turn , read words array if test_all_classes == 'yes': = 1 number_classes_to_check = 45 word_count_array_for_all_classes = [[] z in range(46)] temp_array = [] while <= 45: # opens each file trademark words file_name_class = 'counted_phrases_class' + str(i) + '.txt' temp_array = classes.open_class_file_read_words_to_array(file_name_class) # normalization used because classes have many words , have few words # words/phrases weighted according frequency word_count_array_for_all_classes[i] = classes.normalize_array(temp_array) += 1 else: # print "you didn't enter yes" pass # length_test_data_array = len(test_data_array) # open(file_name_results, 'a').close() # start_writing_results = open(file_name_results, 'a') # start_writing_results.write("the start of test") # start_writing_results.write("\n") # start_writing_results.write("total number of potential items match ") # start_writing_results.write(str(length_test_data_array)) # start_writing_results.write("\n") # start_writing_results.close() top_result = [0 y in range(2)] second_result = [0 y in range(2)] third_result = [0 y in range(2)] top_array_words_not_found = [] second_array_words_not_found = [] third_array_words_not_found = [] counter_for_9vs42 = 0 counter_for_data_errors = 0 top_result = [0 y in range(2)] second_result = [0 y in range(2)] third_result = [0 y in range(2)] top_array_words_not_found = [] second_array_words_not_found = [] third_array_words_not_found = [] actual_class_results = [0 y in range(2)] overall_array_results = [[0 x in range(3)] y in range(4)] actual_class_words_not_found = [] = 1 while <= 45: total_found = 0 total_tm_words_matched = 0 not_found_words = [''] score = 0 n = len(word_count_array_for_all_classes[i]) total_found, total_tm_words_matched, not_found_words, score = classes.analyze_each_line_test_data(test_data_array, n, word_count_array_for_all_classes[i]) if int(score) > 0: if int(score) > top_result[0]: third_result[0] = second_result[0] third_result[1] = second_result[1] third_array_words_not_found = second_array_words_not_found second_result[0] = top_result[0] second_result[1] = top_result[1] second_array_words_not_found = top_array_words_not_found top_result[0] = int(score) top_result[1] = top_array_words_not_found = [''] top_array_words_not_found = not_found_words elif int(score) > second_result[0]: third_result[0] = second_result[0] third_result[1] = second_result[1] third_array_words_not_found = second_array_words_not_found second_result[0] = int(score) second_result[1] = second_array_words_not_found = [''] second_array_words_not_found = not_found_words elif int(score) > third_result[0]: third_result[0] = int(score) third_result[1] = third_array_words_not_found = [''] third_array_words_not_found = not_found_words += 1 overall_array_results[0][0] = top_result[0] overall_array_results[0][1] = top_result[1] overall_array_results[0][2] = top_array_words_not_found overall_array_results[1][0] = second_result[0] overall_array_results[1][1] = second_result[1] overall_array_results[1][2] = second_array_words_not_found overall_array_results[2][0] = third_result[0] overall_array_results[2][1] = third_result[1] overall_array_results[2][2] = third_array_words_not_found # results - including first, second, third choices of engine , original description - written file # create_results_file(file_name_results, overall_array_results, test_data_array) # start_writing_results = open(file_name_results, 'a') # start_writing_results.write("the end of test") # start_writing_results.write("\n") # # start_writing_results.write("\n") # start_writing_results.write("\n") # start_writing_results.close() # print "finished process"
from code i've provided can see parameters provided on python raw_input
, after calculation code creating file in can read result.
i've rewritten can serve on django application, parameters classes
, description
should overwrite raw_input
, result displayed in template, this:
{{ trademark.overall_array_results.top_result }}<br> {{ trademark.overall_array_results.second_result }}<br> {{ trademark.overall_array_results.third_result }}
i'm not sure if i'm doing write thing here, need understand better, can me on come error.
if classes
not "yes", word_count_array_for_all_classes
remains empty list.
Comments
Post a Comment