gpt4 book ai didi

javascript - 从 node.js 运行 Python 脚本时出现 parseError

转载 作者:行者123 更新时间:2023-12-03 04:23:46 25 4
gpt4 key购买 nike

我正在构建一个电影推荐系统。我的推荐引擎是用 Python 编写的。我通过 node.js (Express) 从网站运行它。

Python 代码本身可以工作,这是我从控制台运行它时的输出。它使用 pandas 和 numpy 进行计算,它返回一个矩阵,其中包含电影标题及其与所选电影的相似度,我还打印 hello:

Python command code

在我的网站上,我的正文中有以下HTML:

<form class="test" method="post" action="/test">
<input type="text" name="user[name]">
<input class="button" type="submit" value="Submit">
</form>

JS客户端

(function($) {

$(document).ready(function () {
var btn = $('.button'),
input = $('input');
btn.on('click', function() {
e.preventDefault();
})
})
})(jQuery)

JS服务器端,带有Express

var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var PythonShell = require('python-shell');

var options = {
mode: 'text',
pythonOptions: ['-u'],
scriptPath: "E:/Praca Magisterska/Python",
};

app.use(express.static(path.join(__dirname, '')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));

app.get('/', function (req, res) {
res.sendFile(path.join(__dirname+'/index.html'));
})

app.post('/test', function (req, res) {
console.log(req.body);

PythonShell.run('similarMovies.py', options, function (err, results) {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log('results: %j', results);
});

})

app.listen(3000, function () {
console.log('Example app listening on port 3000!');
})

那么,它是如何工作的。单击“提交 btn”后,我将触发 Node.js 来运行 Python 脚本,然后使用 console.log 结果。不幸的是我遇到了错误,图片在最后。

但是,当我不运行函数时,我会在 Python 末尾编写:

print "hello"
print 2

代码结果解析良好。

Image of command an results

可能有什么问题?我在函数内除以零和其他时遇到的错误?但如果是的话,为什么当我直接从 cmd 运行它时它就可以工作 - python likeMovies.py

这是python代码:

# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np

def showSimilarMovies(movieTitle, minRatings):

# import ratingów z pliku csv
rating_cols = ['user_id', 'movie_id', 'rating']
rating = pd.read_csv('E:/Praca Magisterska/MovieLens Data/ratings.csv', names = rating_cols, usecols = range(3))

# import filmów z pliku csv
movie_cols = ['movie_id', 'title']
movie = pd.read_csv('E:/Praca Magisterska/MovieLens Data/movies.csv', names = movie_cols, usecols = range(2))

# łączenie zaimportowanych ratingów oraz filmów, usuwanie pierwszego wiersza
ratings = pd.merge(movie, rating)
ratings = ratings.drop(ratings.index[[0]])
# konwertowanie kolumn ze stringów na numeric
ratings['rating'] = pd.to_numeric(ratings['rating'])
ratings['user_id'] = pd.to_numeric(ratings['user_id'])

# tworzenie macierzy pokazująceje oceny filmów przez wszystkich użytkowników.
movieRatingsPivot = ratings.pivot_table(index=['user_id'], columns=['title'], values='rating')

# filtrowanie kolumny do obliczania filmów podobnych
starWarsRating = movieRatingsPivot[movieTitle]

# obliczanie korelacji danego filmu z każdym innym i wyrzucanie tych z którymi nic go nie łączy
similarMovies = movieRatingsPivot.corrwith(starWarsRating)
similarMovies = pd.DataFrame(similarMovies.dropna())

# zmiana nazwy kolumny oraz sortowanie według rosnącej korelacji
similarMovies.columns = ['similarity']
similarMovies.sort_values(by=['similarity'], ascending=False)

# tworzenie statystyk dla filmów, size to ilość ocen, a mean to średnia z ocen
# zgrupowane po tytułach
movieStats = ratings.groupby('title').agg({'rating': [np.size, np.mean]})

# popularne filmy, które mają więcej niż 100 ocen
popularMovies = movieStats['rating']['size']>=minRatings

# sortowanie popularnych filmów od najwyższej średniej
movieStats[popularMovies].sort_values(by=[('rating', 'mean')], ascending=False)

# łączenie popularnych filmów z filmami podobnymi do filtrowanego filmu i ich sortowanie
moviesBySimilarity = movieStats[popularMovies].join(similarMovies)
x = moviesBySimilarity.sort_values(by='similarity', ascending=False)
k = x.drop(x.columns[[0, 1]], axis = 1)
k = k.drop(x.index[[0]])
return k

print "hello"
print 2
showSimilarMovies('Star Wars: Episode VI - Return of the Jedi (1983)', 300)

最佳答案

我想通了,只需在 python 文件的开头添加两行即可忽略警告:

import warnings

warnings.filterwarnings('ignore')

现在我的输出就是所需的。

关于javascript - 从 node.js 运行 Python 脚本时出现 parseError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43822389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com