当前位置:网站首页>I have a crossed translation tool in my hand!

I have a crossed translation tool in my hand!

2020-11-10 09:00:00 osc_9nslhqw1

Python The actual combat community

Java The actual combat community

Long press to identify the QR code below , Add as needed

Scan code, pay attention to add customer service

Into the Python community ▲

Scan code, pay attention to add customer service

Into the Java community


source :

https://yuanlehome.github.io/20200612/

What we're going to introduce here is one of the ways in which Linux The word translation tool implemented by the platform , Of course, before you think about implementing a tool that does this , I also searched some on the Internet in Linux Platform implementation of similar open source tools , for example pdfTranslator,popup-dict, But their installation and configuration are more troublesome , And it's not easy to use .

The original intention of this tool is to facilitate me to read some English literature and books , It's very convenient , Considering that sharing can benefit more people , So here is a detailed description of its implementation steps .

The main features of this tool are as follows :

  • Support the translation of English words and phrases to Chinese

  • Delimitation translation , Terminal display

  • Automatically filter special characters such as line breaks in the selected text

  • Only a few Linux Command tool

Here's a diagram to illustrate .

The environment I use is running in VMware Under the virtual machine Linux Distribution version Ubuntu 18.04.3 LTS, So the steps described here may be related to other Linux The implementation in the distribution is slightly different . Now let's take it step by step .

One . Install the necessary commands

  1. xclip

$ sudo apt install xclip

xclip The command establishes a channel between the terminal and the shear board , You can save the contents of the terminal output or file to the clipboard by command , You can also output the contents of the clipboard to the terminal or file . For detailed usage, you can use man xclip, See its manual . Here are some common usages .

$ xclip file_name #  Save the contents of the file to X window Shear plate 
$ xclip -selection c file_name # Save the contents of the file to the external clipboard 
$ xclip -o # X window The contents of the clipboard are output to the terminal display 
$ xclip -selection c -o #  The content of the external shear board is output to the terminal display 

It is worth emphasizing that , What I'm talking about here X window Shear plate , Simply put, the text you select with the mouse will be stored in the clipboard in real time , Use the middle mouse button to paste . And the external shear board is to save you with ctrl+c Copied text ,ctrl+v You can paste . These two places are different .

  1. translate-shell

$ sudo apt install translate-shell

This is the command line version of Google translator , It used to be called Google Translate CLI It's a Google translation ( Default )、 A command line translator that translates by Bing et al . It allows you to access these translation engines on the terminal .translate-shell In most Linux It can be used in all distributions . The common methods are as follows :

$ trans en:zh [word] #  English to Chinese word translation 
$ trans en:zh -b [text] #  Brief output , Translate the text 

It should be noted that , The use of this translation tool requires you to be able to access the Internet , Or by modification translate-shell The default translation engine for , The specific method will not be elaborated here .

Two . Programming to realize

The whole idea of this tool is C Program real-time detection of mouse button dynamic , When it is detected that the user has used the mouse to select a piece of text , call shell Script get X window The content of the clipboard is translated and output to the terminal display .

1. Locate the mouse device file

Mouse as input device . The information can be found in the file /proc/bus/input/devices in , Use the following command to view :

$ sudo cat /proc/bus/input/devices
I: Bus=0011 Vendor=0002 Product=0013 Version=0006
N: Name="VirtualPS/2 VMware VMMouse"
P: Phys=isa0060/serio1/input1
S: Sysfs=/devices/platform/i8042/serio1/input/input4
U: Uniq=
H: Handlers=mouse0 event2 
B: PROP=0
B: EV=b
B: KEY=70000 0 0 0 0
B: ABS=3

Among them Handlers Value event2 It means that you can be in /dev/input/event2 Read the state of the mouse under the file . It should be noted that , For different devices , The file that reads the state of the mouse may be different , For example, it could be /dev/input/event3 . We can use the following command to find out which one your mouse corresponds to event.

$ sudo cat /dev/input/event2 | hexdump #  Change the number when testing 

such as , When I run the above command , I move the mouse 、 Press the left mouse button / In the key / Right click , The terminal will output some values , This means that event2 The file is my mouse . If the mouse doesn't respond , It means that this is not . In this way, you can find the corresponding mouse event file .

2. Linux Get key response under

stay Linux The kernel ,input For equipment input_dev Description of structure , Use input When the subsystem implements the input device driver , The core work of the driver is to report the buttons to the system 、 Touch screen 、 keyboard 、 Mouse and other input events (event, adopt input_event Description of structure ), No longer need to care about file operation interface , because input The subsystem has completed the file operation interface Linux/input.h This document defines event The structure of events ,API And the coding of standard keys .

//  For the definition of structure, see  input.h
struct input_event
{
    struct timeval time; //  Key time 
    __u16 type;          //  Event type 
    __u16 code;          //  What buttons do you want to simulate 
    __s32 value;         //  Press or release 
};

//  The following macro definition is shown in  input-event-coses.h
// type
#define EV_KEY 0x01
#define EV_REL 0x02
#define EV_ABS 0x03
// ...

// code
#define BTN_LEFT 0x110
#define BTN_RIGHT 0x111
#define BTN_MIDDLE 0x112
// ...

// value
#define MSC_SERIAL 0x00
#define MSC_PULSELED 0x01
// ...

Here's a little bit about type, Refers to the type of event , Common types of events are :EV_KEY, Key events , Like the keys on the keyboard ( Press which key ), The left and right mouse button ( Whether to hit ) etc. ;EV_REL, Relative coordinates , Mainly refers to the mouse movement event ( Relative displacement );EV_ABS, Absolute coordinates , It mainly refers to the mobile event of touch screen .

3. To write C Program

Now you can write a program to detect the dynamic of the mouse . First of all, in your users ~ Create folder under directory Translator. stay Translator Create a ct.c Source file , The code is as follows :

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/input.h>
#include <fcntl.h>

int main(void)
{
    int keys_fd;
    struct input_event t;

    //  Note that the files opened here will be changed according to your own device 
    keys_fd = open("/dev/input/event2", O_RDONLY);
    if (keys_fd <= 0)
    {
        printf("open /dev/input/event2 error!\n");
        return -1;
    }

    while (1)
    {
        read(keys_fd, &t, sizeof(t));
        if (t.type == EV_KEY)              //  There is a key to press 
            if (t.code == BTN_LEFT)        //  Left mouse button 
                if (t.value == MSC_SERIAL) //  Release 
                    //  Call external shell Script 
                    system("~/Translator/goTranslate.sh");
    }
    close(keys_fd);
    return 0;
}

And then the call gcc The compiler generates executable files ct :

$ gcc ct.c -o ct

4. To write shell Script translates the content of the clipboard

stay Translator Built in goTranslate.sh file , The contents are as follows :

#!/bin/bash

str_old=$(cat ~/Translator/lastContent)
str_new=$(xclip -o 2>/dev/null | xargs)
if [[ "$str_new" != "$str_old" && $str_new ]]; then
    echo -e "\n"
    count=$(echo "$str_new" | wc -w)
    if [ "$count" == "1" ]; then
        echo -n -e "$str_new " >>~/Translator/words
        echo "$str_new" | trans :zh-CN | tail -1 | cut -c 5- | sed "s,\x1b\[[0-9;]*[a-zA-Z],,g" | tee -a ~/Translator/words
    else
        echo "$str_new" | trans :zh-CN -b
    fi
    echo "$str_new" >~/Translator/lastContent
fi

The principle is very simple , The reader understands . Here we have to be in Translator Create a lastContent.txt File as cache , The purpose is to get the translated text content of the last call when calling the script this time , If it is the same as the translated text of this call , No translation will be carried out this time .

  1. Set up ct Alias

Here you can run the program with the following command :

$ sudo ~/Translator/ct

But because each run has to output such a long command , So we have ~/.bashrc Add the following command to the file .

alias ct='sudo ~/Translator/ct'

such , In the future, you can input in the command line every time you read English literature :

$ ct

3、 ... and . Conclusion

Here are some tips . You can use this tool more easily . such as , Set the terminal to the top and shrink to the right size , In this way, the terminal screen will not block our sight when reading the literature word translation .

It's worth noting that , Because I am completely for the convenience of their own use , And when you come up with such a tool, you just touch Linux The system is less than two weeks , So the implementation is a bit clumsy for experienced friends , Please understand .

I think this tool is very convenient to use , Do you think? ?

source  :

https://yuanlehome.github.io/20200612/

 Programmer column   Scan code and pay attention to customer service   Press and hold to recognize the QR code below to enter the group 

Recent highlights are recommended :  

  My girlfriend thinks the annual salary is 50 Ten thousand is the average level , What do I do ?

  The sexy goddess of the biggest straight men forum in China overturned

 IntelliJ IDEA Fully optimized settings , Efficiency bars !

  Very useful Python skill


Here's a look Good articles to share with more people ↓↓

版权声明
本文为[osc_9nslhqw1]所创,转载请带上原文链接,感谢