Python划词翻译通过socket发送到Android端显示

 实现不难,原理python 通过socket与Android获取连接 

Python 作为Server端 ,Android作为Client 端接收Python发送过来的数据。Android需要知道Python server端的IP地址和的端口号 。 端口号可以在Python随意指定,不冲突就行。

Python设置热键,获取粘贴板的内容,即要翻译的单词。至于翻译有两种方式,第一种Python获取单词,将单词发送到Android端,由Android端请求翻译API。第二种,由Python获取单词,并且由Python请求API翻译,将单词和释义都发送到Android。本文采用后者,原因是,百度翻译API提供了Python请求的实例,可以说是傻瓜式操作了。

接下来上Python代码:

import socket
import keyboard

import pyperclip

import http.client
import hashlib
import urllib
import random
import json

# 先设置 热键
plist = []


def getData():
    print("触发事件")
    # ctrl c c 会触发两次事件取第二次 内容就是最新的粘贴板上的内容
    data = pyperclip.paste()
    plist.append(data)
    if len(plist) > 1:
        msg = plist[1]  #原始值
        try:
            appid = ''  # 填写你的appid
            secretKey = ''  # 填写你的密钥

            httpClient = None
            myurl = '/api/trans/vip/translate'

            fromLang = 'auto'  # 原文语种
            toLang = 'zh'  # 译文语种
            salt = random.randint(32768, 65536)
            q = msg
            sign = appid + q + str(salt) + secretKey
            sign = hashlib.md5(sign.encode()).hexdigest()
            myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
                q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
                salt) + '&sign=' + sign
            httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
            httpClient.request('GET', myurl)

            # response是HTTPResponse对象
            response = httpClient.getresponse()
            result_all = response.read().decode("utf-8")
            result = json.loads(result_all)
            transfer = result.get("trans_result")[0].get("dst")
            print(transfer)   #翻译结果
            send_data =q+"+"+transfer






        except Exception as e:
            print(e)

        print("发送" + send_data + "成功")
        conn.send(send_data.encode())  # 把接收到数据原封不动的发送回去
        plist.clear()


# wait里也可以设置按键,说明当按到该键时结束

def getipaddrs(hostname):  # 只是为了显示IP,仅仅测试一下
    result = socket.getaddrinfo(hostname, None, 0, socket.SOCK_STREAM)
    return [x[4][0] for x in result]


host = ''  # 为空代表为本地host
hostname = socket.gethostname()
hostip = getipaddrs(hostname)
print('host ip', hostip)  # 应该显示为:127.0.1.1
port = 23411  # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(4)

while True:
    conn, addr = s.accept()
    print('Connected by', addr)
    data = conn.recv(1024)
    # 当我确认client 和我建立连接 我将数据发给client

    print("接收到Android 发送的数据为" + data.decode())

    keyboard.add_hotkey('ctrl+c', getData)

    if not data:
        break
    keyboard.wait()

    conn.close()

其中融合了百度翻译API提供的例子

接下来是简单的Android 部分代码 

package com.yzj.transferapp;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class MainActivity extends Activity {

    private String ip = "192.168.3.72";
    private int TCP_PORT = 23411;
    private  Handler  handler;
    private TextView word,transfer_text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
// ask landscape
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
//keep screen On
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_main);

        transfer_text=findViewById(R.id.trans_text);
        word=findViewById(R.id.re_word);
        word.setText("ces");

        new Thread(runnable).start();


        handler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(Message msg) {
                String msg_word = "";
                if (msg.what == 1){
                    System.out.println("收到了" +
                            "");
                    msg_word = msg.getData().get("word").toString();
                    System.out.println(msg_word);

                    String src ="";
                    String transfer ="";
                    int count=0;
                    for(int i=0;i40&&src.length()<80){
                        word.setTextSize(40);
                    }
                    if(src.length()>80){
                        word.setTextSize(20);
                    }



                    word.setText(src);


                    if(transfer.length()>40){
                        transfer_text.setTextSize(40);
                    }


                    transfer_text.setText(transfer);
                }
            }
        };

    }

    private void runTcpClient(String IP, final int TCP_PORT) {
        try {

//            建立连接
            Socket s = new Socket(IP, TCP_PORT);//注意host改成你服务器的hostname或IP地址
            if (true == s.isConnected()) {
//                能连上再进行操作
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                //send output msg
                String outMsg = "TCP connecting to " + TCP_PORT + System.getProperty("line.separator");
                out.write(outMsg);//发送数据
                out.flush();

                Log.i("TcpClient", "sent: " + outMsg);
                while (true) {
                    //accept server response
                    // serverSocket.isConnected 代表是否连接成功过
                    // 判断 Socket 是否处于连接状态
                    if (true == s.isConnected() && false == s.isClosed()) {
                        // 客户端接收服务器端的响应,读取服务器端向客户端的输入流
                        InputStream isRead = s.getInputStream();
                        // 缓冲区
                        byte[] buffer = new byte[isRead.available()];
                        // 读取缓冲区
                        if (isRead != null) {
                            isRead.read(buffer);
                            // 转换为字符串
                            String responseInfo = new String(buffer);

                            if (responseInfo.length() != 0) {
                                Log.i("Socket Server", responseInfo);
                                // 日志中输出
                                System.out.println("这是接收的数据" + responseInfo);
//                                接收数据发送给主线程

//
//
                                Message text = new Message();
                                text.what = 1;
                                Bundle bundle = new Bundle();
                                bundle.putString("word", responseInfo);
                                text.setData(bundle);
                                handler.sendMessage(text);


                            }

                        }
                    } else {
//                没连上
                        System.out.println("没连上");

                    }


                }
            }



        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            runTcpClient(ip, TCP_PORT);
        }
    };

}

你可能感兴趣的:(笔记,python,android,开发语言)