简体   繁体   English

Flask中的外部模块-TypeError:“系列”对象不可调用

[英]External Module into Flask - TypeError: 'Series' object is not callable

I am looking to bring in an external module into flask 'reommendationSearch', which essentially calculates the similarity of movie titles based frequency of similar key words 我希望将外部模块引入烧瓶'reommendationSearch',该模块实质上是根据相似关键字的出现频率来计算电影标题的相似性

My issue arises when attempting to integrate this with flask, where 'title' is 'search_string'. 尝试将其与flask集成时出现了我的问题,其中“标题”为“ search_string”。 Error: 'AttributeError: 'NoneType' object has no attribute 'indices'. 错误:'AttributeError:'NoneType'对象没有属性'indices'。 Here is the traceback: 这是回溯:

Traceback Snapshot 追溯快照

Flask Code: 烧瓶代码:

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]

You have an undefined title variable you're not declaring in your code. 您有未在代码中声明的未定义title变量。

If the title is something you would get from the user via 'POST' request, consider adding a param to the POST query and passing it into the "reommendationSearch" class. 如果标题是您可以通过“ 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

EDIT: I've just noticed you're using wtforms, in any case the title is not being passed into the "get_recommendations" function because it's external to the class and hence not defined within said class' scope. 编辑:我刚刚注意到您正在使用wtforms,无论如何标题都不会传递到“ get_recommendations”函数中,因为它在类的外部,因此未在所述类的范围内定义。

In any case, the solution is to ensure that the title variable is defined inside of the class. 无论如何,解决方案是确保在类内部定义title变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM