列表索引在django中超出范围

时间:2016-04-27 18:26:24

标签: django python-2.7

我正在使用Django作为后端实现Sentiment分析Web应用程序。 Python版本是2.7。 Django版本是1.9.5。操作系统是linux(Ubuntu)。我是Django的新手,我从github找到了以下代码。问题是,当我在文本框中输入一个句子来向我显示它的情绪时,我收到以下错误。

IndexError at /
list index out of range
Request Method: GET
Request URL:    http://127.0.0.1:8000/?search_text=hello+world
Django Version: 1.9.5
Exception Type: IndexError
Exception Value:    
list index out of range
Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/models/query.py in __getitem__, line 297
Python Executable:  /usr/bin/python
Python Version: 2.7.6
Python Path:    
['/media/ehsan/New Volume/thesis/Django tutorial/SentimentAnalysis_DjangoApp-master',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/home/ehsan/.local/lib/python2.7/site-packages',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PILcompat',
 '/usr/lib/python2.7/dist-packages/gtk-2.0',
 '/usr/lib/pymodules/python2.7',
 '/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
 '/rwthfs/rz/SW/UTIL.common/Python/2.7.9/x86_64/lib/python2.7/site-packages']

以下是Models.py

上的代码
from django.db import models
import nlpapp.sentiment_mod as s

# Create your models here.
class Sentiment(models.Model): 

    text = " "

    # function that receives text and spits out pos or neg
    def analysis(self, text):
        if s.Result(text)[1] is 'Neutral': 
            self.text = "Neutral"

        elif s.Result(text)[1] is 'Positive': 
            self.text = "Positive"

        else: 
            self.text = "Negative"

    def __str__(self):
        return self.text

Result是一个函数sentiment.py,它返回句子的情绪。 这是views.py。我猜这个错误是由这个页面引起的。

from django.shortcuts import render, render_to_response

# Create your views here.
from nlpapp.models import Sentiment
from django.views.generic import ListView

class Senty(ListView):
    """docstring for Senty"""
    model = Sentiment
    context_object_name = "senti"

    def dispatch(self, request, *args, **kwargs):
        return super(Senty, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        #Get the current context.
        context = super(Senty, self).get_context_data(**kwargs)

        search_text = "" # Assume no search
        if self.request.method == "GET": 
            search_text = self.request.GET.get("search_text", "").strip()
            print("1", search_text, type(search_text))

        if search_text != "": 
            # get the result of the analysis 
            a = Sentiment.objects.all()[0]
            a.analysis(search_text)
            analysis_result = a.text
            print("2", analysis_result)
            # analysis_result = [a]
            # print("2", analysis_result[0].text)
        else: 
            analysis_result = []
        print("3", analysis_result)

        # adding items to context for display
        context["search_text"] = search_text
        context["analysis_result"] = analysis_result

        return  context

以下是错误发生的行

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/?search_text=Hello+world

Django Version: 1.9.5
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'nlpapp',
 'django.contrib.humanize')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')



Traceback:

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/media/ehsan/New Volume/thesis/Django tutorial/SentimentAnalysis_DjangoApp-master/nlpapp/views.py" in dispatch
  32.       return super(Senty, self).dispatch(request, *args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/views/generic/list.py" in get
  174.         context = self.get_context_data()

File "/media/ehsan/New Volume/thesis/Django tutorial/SentimentAnalysis_DjangoApp-master/nlpapp/views.py" in get_context_data
  45.           a = Sentiment.objects.all()[0]

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in __getitem__
  297.         return list(qs)[0]

Exception Type: IndexError at /
Exception Value: list index out of range 

1 个答案:

答案 0 :(得分:0)

检查完代码后,我假设您使用的django模型略有不同。 django模型是数据库表的django表示。并作为文件says

  

模型中最重要的部分 - 也是模型中唯一的必需部分 - 是它定义的数据库字段列表。

但是从这一行 -

class Sentiment(models.Model): 

    text = " "

    # function that receives text and spits out pos or neg
    def analysis(self, text):
        if s.Result(text)[1] is 'Neutral': 
            self.text = "Neutral"

        elif s.Result(text)[1] is 'Positive': 
            self.text = "Positive"

        else: 
            self.text = "Negative"

    def __str__(self):
        return self.text

我可以说你没有在模型中定义任何数据库字段。而你只是用它来进行输入文本分析,对吧?所以,在你的情况下Sentiment.objects.all()既不起作用也没有任何意义。因为我不确定是否有数据库表。

因此,如果您需要模型,我建议您查看有关django模型的these tutorialsthese documentation pages。或者,如果您只需要一个功能来分析输入文本,那么您可以创建一个自定义的python类,而不是django模型,并将其用于此。