给Flask加上百度翻译功能,这样可以用中文进行搜索了

上一篇博客:Flask之手搓bootstrap翻页-CSDN博客 里,对 OMDb API - The Open Movie Database 的搜索,只能使用英文,才能搜索出电影信息,如果使用中文,是搜索不到结果的。这里就需要使用翻译,把中文电影名翻译成英文电影名。

这里使用百度翻译,百度翻译量少的话是免费的,百度翻译开放平台,而且有python的示例代码,可以直接照抄。

# -*- coding: utf-8 -*-

# This code shows an example of text translation from English to Simplified-Chinese.
# This code runs on Python 2.7.x and Python 3.x.
# You may install `requests` to run this code: pip install requests
# Please refer to `https://api.fanyi.baidu.com/doc/21` for complete api document

import requests
import random
import json
from hashlib import md5

# Set your own appid/appkey.
appid = 'INPUT_YOUR_APPID'
appkey = 'INPUT_YOUR_APPKEY'

# For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
from_lang = 'en'
to_lang =  'zh'

endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path

query = 'Hello World! This is 1st paragraph.\nThis is 2nd paragraph.'

# Generate salt and sign
def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()

salt = random.randint(32768, 65536)
sign = make_md5(appid + query + str(salt) + appkey)

# Build request
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

# Send request
r = requests.post(url, params=payload, headers=headers)
result = r.json()

# Show response
print(json.dumps(result, indent=4, ensure_ascii=False))

只需要在搜索路由里,将form表单传递过来的中文搜索词翻译成英文即可。如果是英文,那就让它再翻译一遍,一般是没有变化。

详细代码如下。

app.py

from flask import Flask, render_template, request
import requests
import math
import json
import random
from hashlib import md5

app = Flask(__name__)


@app.route('/', methods=["GET"])
# @app.route('/?s=&page=', methods=["GET"])
def main():
    s = request.args.get("s")
    page = request.args.get("page")
    if page is None:
        page = 1
    else:
        page = int(request.args.get("page"))
    if s is None:
        s = 'superman'
    # Here is your key: 4ee0241e
    # OMDb API: http://www.omdbapi.com/?i=tt3896198&apikey=4ee0241e
    # rawData = requests.get("http://www.omdbapi.com/?apikey=4ee0241e&s=batman&page=1")
    rawData = requests.get(f"http://www.omdbapi.com/?apikey=4ee0241e&s={s}&page={page}")
    movies = rawData.json()
    if movies["Response"] == "True":
        pages = math.ceil(int(movies["totalResults"]) / 10)
    else:
        pages = 0
    data = dict(
        movies=movies,
        active1="active",
        active2="",
        pages=pages,
        page=page,
        s=s,
    )
    return render_template("index.html", data=data)


@app.route('/', methods=["POST"])
def search():
    s = request.form["name"]
    en_s = fanyi(s)
    page = 1
    rawData = requests.get(f"http://www.omdbapi.com/?apikey=4ee0241e&s={en_s}&page={page}")
    movies = rawData.json()
    if movies["Response"] == "True":
        pages = math.ceil(int(movies["totalResults"]) / 10)
    else:
        pages = 0
    data = dict(
        movies=movies,
        active1="active",
        active2="",
        pages=pages,
        page=page,
        s=s,
    )
    return render_template("index.html", data=data)


def fanyi(s):
    # Set your own appid/appkey.
    appid = 'INPUT_YOUR_APPID'
    appkey = 'INPUT_YOUR_APPKEY'
    # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
    from_lang = 'zh'
    to_lang = 'en'

    endpoint = 'http://api.fanyi.baidu.com'
    path = '/api/trans/vip/translate'
    url = endpoint + path

    # query = 'Hello World! This is 1st paragraph.\nThis is 2nd paragraph.'
    query = s

    # Generate salt and sign
    def make_md5(sm, encoding='utf-8'):
        return md5(sm.encode(encoding)).hexdigest()

    salt = random.randint(32768, 65536)
    sign = make_md5(appid + query + str(salt) + appkey)

    # Build request
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

    # Send request
    r = requests.post(url, params=payload, headers=headers)
    result = r.json()

    # Show response
    # print(json.dumps(result["trans_result"][0]["dst"], indent=4, ensure_ascii=False))
    # print(json.dumps(result, indent=4, ensure_ascii=False))  # "superman"
    # print(result["trans_result"][0]["dst"])   # superman
    return result["trans_result"][0]["dst"]


@app.route('/')
def movie_by_title(imdbID):
    # rawData = requests.get("http://www.omdbapi.com/?apikey=4ee0241e&i={}".format(imdbID))
    rawData = requests.get(f"http://www.omdbapi.com/?apikey=4ee0241e&i={imdbID}")
    movie = rawData.json()
    data = dict(
        movie=movie,
        active1="",
        active2="active",
    )
    return render_template("movie.html", data=data)


if __name__ == '__main__':
    app.run(debug=True)

footer.html

header.html


母版

nav.html

home.html




    {% block head %}
        {% include './common/header.html' %}
    {% endblock %}
    


{% block nav %}
    {% include './common/nav.html' %}
{% endblock %}
{% block content %} {% endblock %}
{% block footer %} {% include './common/footer.html' %} {% endblock %}

movie.html

{% extends "common/home.html" %}

{% block content %}
    
...
{{ data["movie"].Title }}

Year:{{ data["movie"].Year }}

Runtime:{{ data["movie"].Runtime }}

Actors:{{ data["movie"].Actors }}

{{ data["movie"].Actors }}

{{ data["movie"].Year }}

{{ data["movie"].Plot }}

{% endblock %}

给Flask加上百度翻译功能,这样可以用中文进行搜索了_第1张图片

index.html

{% extends "common/home.html" %}

{% block content %}
    {% for movie in data["movies"].Search %}
        
...
{{ movie.Title[:35] }}

{{ movie.Year }}

详情
{% endfor %} {# 翻页 #}
{% endblock %}

index.html模板里,加上了没有结果时的代码:

{% else %}
  搜索: {{ data.s }} 的结果为空!
{% endif %}

把数字放前面,反而可以搜到,不知道翻译是咋翻译的。

 

你可能感兴趣的:(Flask,flask,python,百度翻译)