从node.js运行Python脚本时发生parseError [英] parseError when running Python script from node.js

查看:33
本文介绍了从node.js运行Python脚本时发生parseError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建电影推荐器.我的推荐器引擎是用Python编写的.而且我正在通过node.js(Express)在网站上运行它.

I am constructing a movie recommender. My recommender engine is written in Python. And I am running it from website through node.js (Express).

python代码本身起作用,这是我从控制台运行它时的输出.它使用pandas和numpy进行计算,它返回一个矩阵,该矩阵包含电影的标题及其与所选电影的相似性,并且我还会打个招呼:

The python code itselfs work and here is the output when I am running it from a console. It is using pandas and numpy for calculations it returns a matrix with title of movie and its similarity to a chosen movie, and I also print hello:

Python命令代码

在我的网站上,我的正文中包含 HTML :

On my website I have following HTML in body:

<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 结果.不幸的是,我得到了错误,最后是图片.

So, how it works. On clicking submit btn I am firing my node.js to run a python script and then console.log the results. Unfortunately I am getting errors, image at the end.

但是,当我不运行函数而不是运行函数时,我只是在Python的末尾编写了代码:

However, when I do not run function and instead of it I write at the end of my Python just:

print "hello"
print 2

代码结果解析良好.

命令结果图像

可能是个问题?我在函数中除以零和其他除法得到的错误?但是,如果是为什么,那么当我直接从cmd运行它时它会起作用- python likeMovies.py

What could be an issue? Erros that I am getting with dividing by zero and other inside a funcion? But if yes why then it is working when I run it directly from cmd - python similarMovies.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文件的开头添加了两行来忽略警告:

I figured it out, just added two lines at the beggining of python file to ignore warnings:

import warnings

warnings.filterwarnings('ignore')

现在我的输出是所需的.

Now my output is what was desired.

这篇关于从node.js运行Python脚本时发生parseError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆