外部模块进入Flask - TypeError:'Series'对象不可调用

时间:2018-02-20 18:54:57

标签: python flask

我希望将一个外部模块引入烧瓶'reommendationSearch',它基本上根据类似关键词的频率计算电影片名的相似性

我的问题出现在尝试将其与烧瓶集成时,其中'title'是'search_string'。 错误: 'AttributeError:'NoneType'对象没有属性'indices'。这里是 回溯:

Traceback Snapshot

烧瓶代码:

from flask import Flask, render_template, flash, redirect, url_for, session, logging, request
from wtforms import Form,StringField, TextAreaField, PasswordField, validators
from ReccomendationTest import reommendationSearch
# Parse HTML Page via Flask
@app.route('/')
def index():
    return render_template('home.html')

class searchForm(Form):
    search = StringField('Movie Title:')

@app.route('/about',methods = ['GET','POST'])    
def search_results():
    form = searchForm(request.form)
    search_string = form.search.data 
    search_results = reommendationSearch()
    output_results = search_results.get_recommendations(search_string)
    results=[]
    if request.method == 'POST':
        return(output_results)

if __name__ =="__main__":
    app.secret_key='secret123'
    app.run()

ReccomendationTest:

import pandas as pd
import numpy as np
import os

from ast import literal_eval
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel


class reommendationSearch():
        #Import the Open Source Dataset
        os.chdir('C:\\Users\parmi\Documents\Python Scripts')
        org_data = pd.read_csv('tmdb_5000_movies.csv')

        #Define a TF-IDF Vectorizer Object. Remove all english stop words such as 'the', 'a'
        tfidf = TfidfVectorizer(stop_words='english')

    #Replace NaN with an empty string
    org_data['overview'] = org_data['overview'].fillna('')

    #Construct the required TF-IDF matrix by fitting and transforming the data
    tfidf_matrix = tfidf.fit_transform(org_data['overview'])

    # Compute Consine Similarirty Matrix
    cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)

    indices = pd.Series(org_data.index, index=org_data['title']).drop_duplicates()

    # Function that takes in movie title as input and outputs most similar movies
    def get_recommendations(title,self):
            #self.user_input = user_input
            # Get the index of the movie that matches the title
        idx = self.indices[title]

            # Get the pairwsie similarity scores of all movies with that movie
        sim_scores = list(enumerate(self.cosine_sim[idx]))

            # Sort the movies based on the similarity scores
        sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)

            # Get the scores of the 10 most similar movies
        sim_scores = sim_scores[1:11]


            # Sort the movies based on the similarity scores
        sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)

            # Get the movie indices
        movie_indices = [i[0] for i in sim_scores]

            # Return the top 10 most similar movies
        return self.org_data['title'].iloc[movie_indices]

1 个答案:

答案 0 :(得分:0)

您的代码中没有声明未定义的title变量。

如果标题是您通过“POST”请求从用户处获得的,请考虑在POST查询中添加一个参数并将其传递到“reommendationSearch”类。

@app.route('/about',methods = ['GET','POST'])    
def search_results():
    req_title = request.args.get('title')
    search_results = reommendationSearch(req_title)
...

class reommendationSearch(title):
    # And here goes the rest of your code
编辑:我刚刚注意到你正在使用wtforms,在任何情况下都没有将标题传递给“get_recommendations”函数,因为它在类的外部,因此没有在所述类的范围内定义。

无论如何,解决方案是确保在类内部定义title变量。