Coder Social home page Coder Social logo

felixonmars / ydcv Goto Github PK

View Code? Open in Web Editor NEW
505.0 18.0 91.0 85 KB

YouDao Console Version - Simple wrapper for Youdao online translate (Chinese <-> English) service API, as an alternative to the StarDict Console Version(sdcv).

License: GNU General Public License v3.0

Python 100.00%

ydcv's Introduction

YouDao Console Version

Simple wrapper for Youdao online translate (Chinese <-> English) service API, as an alternative to the StarDict Console Version(sdcv).

注意

本工具已经停止公共服务。用户若要继续使用,需申请一个私人的有道智云 API Key配置使用。 大致步骤为: 翻译实例-创建实例-选"文本翻译", 我的应用-创建应用-接入方式:API-选择绑定刚才创建的自然语言翻译服务-文本翻译实例。 得到的应用ID / 应用密钥即为本工具的YDAPPID/YDAPPSEC

本工具可通过环境变量YDCV_YOUDAO_APPIDYDCV_YOUDAO_APPSEC和ini文件方式配置key。配置文件默认为~/.ydcv,也可用--config指定。 配置文件例子:

[YDCV]
YDAPPID=123456
YDAPPSEC=abcd1234

Usage

$ ydcv --help
usage: ydcv.py [-h] [-f] [-s] [-S] [-r] [-p {festival,mpg123,sox,mpv}]
               [-a {auto,uk,us}] [-x] [--color {always,auto,never}]
               [-F {zh-CHS,ja,EN,ko,fr,ru,pt,es,vi,de,ar,id}]
               [-t {zh-CHS,ja,EN,ko,fr,ru,pt,es,vi,de,ar,id}]
               [words [words ...]]

Youdao Console Version

positional arguments:
  words                 words to lookup, or quoted sentences to translate.

optional arguments:
  -h, --help            show this help message and exit
  -f, --full            print full web reference, only the first 3 results
                        will be printed without this flag.
  -s, --simple          only show explainations. argument "-f" will not take
                        effect.
  -S, --speech          print URL to speech audio.
  -r, --read            read out the word with player provided by "-p" option.
  -p {festival,mpg123,sox,mpv}, --player {festival,mpg123,sox,mpv}
                        read out the word with this play.Default to 'festival'
                        or can be 'mpg123', 'sox', 'mpv'.-S option is required
                        if player is not festival.
  -a {auto,uk,us}, --accent {auto,uk,us}
                        set default accent to read the word in. Default to
                        'auto' or can be 'uk', or 'us'.
  -x, --selection       show explaination of current selection.
  --color {always,auto,never}
                        colorize the output. Default to 'auto' or can be
                        'never' or 'always'.
  -F {zh-CHS,ja,EN,ko,fr,ru,pt,es,vi,de,ar,id}, --from {zh-CHS,ja,EN,ko,fr,ru,pt,es,vi,de,ar,id}
                        Translate from specific language. Default: EN
  -t {zh-CHS,ja,EN,ko,fr,ru,pt,es,vi,de,ar,id}, --to {zh-CHS,ja,EN,ko,fr,ru,pt,es,vi,de,ar,id}
                        Translate to specific language. Default: zh-CHS
  -c CONFIG, --config CONFIG
                        Config file contains API AppKey / SecKey. Default: ~/.ydcv
          

翻译支持的语言列表

--from--to参数可以指定特定语言之间相互翻译,但只有中文结果有词典内容

语言 代码 语言 代码 语言 代码 语言 代码
中文 zh-CHS 葡萄牙文 pt 韩文 ko 德文 de
日文 ja 西班牙文 es 法文 fr 阿拉伯文 ar
英文 EN 越南文 vi 俄文 ru 印尼文 id

Installation

pip install ydcv

Environment

  • Python ( >=2.7, 3.x )

Similar Projects on github

Lang Project Author
Go ydgo boypt
RUST ydcv-rs farseerfc
RUST ydcv-rust passchaos
Powershell ydcv.ps1 atupal
BASH ydcv-bash-version MasterCsquare
Perl ydcv JaHIY
C cydcv proudzhu
C++ ydcv-cpp proudzhu
Vim ydcv.vim bennyyip
Erlang ydcv-el zhenglinj
Haskell ydcv-hs proudzhu

ydcv's People

Contributors

atupal avatar axionl avatar bitdeli-chef avatar boypt avatar brunobell avatar cute-jumper avatar evincemoi avatar felixonmars avatar firef0x avatar freed-wu avatar fxcoudert avatar fykec avatar hellocodem avatar ideal avatar jyaken avatar k6f avatar lilydjwg avatar sequencer avatar toctan avatar wfxr avatar wsyxbcl avatar yuex avatar zhsj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ydcv's Issues

Please add howto leave interaction mode in the help list.

As you can see, when I type ydcv in my terminal, it just get into the interaction mode. But the problem is
when I'm in interaction mode, I type a world and get the meaning, but I try to type CTRL-C, I can't quit
I have to type CTRL-Z to suspend. I think @felixonmars should write the method in the help list or the README file.

remove py3 branch

ydcv.py is now directly compatible with both 2.7 and 3.x, the py3 branch is unnecessary.

by the way, what version of python shall we declare at shebang line ?

#!/usr/bin/env python2.7
or
#!/usr/bin/env python

I prefer the latter one.

Proposal: Provide option "--list-suggestions" to suggest the word.

@felixonmars 大神,您好!

设想这样一个场景:在其它地方看到了一个单词 aardvark ,想知道是什么意思,但身边又没有词典供查询。回到电脑前想查询这个词时,一下子又忘了这个词具体怎么拼,只记得是 aard 开头。

当增加了这个参数后, ydcv 会把单词建议以以下方式输出。

$ ydcv --list-suggestions aard

aard
aardman
aardman animations
aardvark
aardwolf

一般来说看一遍单词就能从几个类似单词中辨认出来比看一遍单词就能拼出来要容易一些,所以我觉得这个参数还是有一定的实际用处的。

不知道您的意见如何?期待您的回复! 😍

此致! 🙇

specify detailed python veision

The shebang line specifies python2.
This is vague.
For example, the format() method of strings used in the script is not available in earlier versions of python2.
(I cannot remembered when python2 introduces this method, 2.6 or 2.7?)

Can I use your API key directly?

我最近给我的qq机器人程序加了个有道词典功能,是在你的代码基础上修改的(把print改成添加到字符串尾端,处理完之后发送到qq)。现在问题来了,我这人比较懒,可以直接用你的API key吗?

ydcv 0.6 fails to run on macOS Python 2.7.10

Running ydcv 0.6 on macOS (all versions from 10.12 to 10.14) with the system Python (Python 2.7.10 (default, Aug 17 2018, 19:45:58)) gives the following error:

==> /usr/local/Cellar/ydcv/0.6/bin/ydcv 你好
  File "/usr/local/Cellar/ydcv/0.6/bin/ydcv", line 117
SyntaxError: Non-ASCII character '\xe6' in file /usr/local/Cellar/ydcv/0.6/bin/ydcv on line 117, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
Error: ydcv: failed

The error can be reproduced with Python 2.7.15 from Homebrew. The script works, however, with Python 3.7.2.

新手求助 git bash 中遇到的问题

你好

python ydcv.py apple
appleTraceback (most recent call last):
  File "ydcv.py", line 217, in <module>
    lookup_word(word)
  File "ydcv.py", line 177, in lookup_word
    print_explanation(json.loads(data), options)
  File "ydcv.py", line 104, in print_explanation
    print(" UK: [{0}]".format(_c(_b['uk-phonetic'], 'yellow')), end=',')
UnicodeEncodeError: 'gbk' codec can't encode character '\xe6' in position 7: illegal multibyte sequence

是哪里出了问题

[bug] KeyError

$ sudo pacman -S ydcv
$ ydcv
Traceback (most recent call last):
  File "/usr/bin/ydcv", line 33, in <module>
    sys.exit(load_entry_point('ydcv==0.7', 'console_scripts', 'ydcv')())
  File "/usr/lib/python3.10/site-packages/ydcv.py", line 353, in main
    sec = config["YDCV"]
  File "/usr/lib/python3.10/configparser.py", line 964, in __getitem__
    raise KeyError(key)
KeyError: 'YDCV'

Proposal: Provide Z Shell auto completion file for ydcv

Hello, @felixonmars !

Since there is no Z Shell auto completion file for ydcv, Z Shell would auto complete filename of the current directory by default. Then some odd auto completions are shown when using ydcv. Would you please provide Z Shell auto completion file for ydcv?

Hope for your reply! Wish you a happy Lantern Festival! 🏮

Yours sincerely!


不小心用了中文回复了。⊙﹏⊙b 那就一直用中文吧:

  • 列出所有参数项
  -h, --help            show this help message and exit
  -f, --full            print full web reference, only the first 3 results
                        will be printed without this flag.
  -s, --simple          only show explainations. argument "-f" will not take
                        effect
  -x, --selection       show explaination of current selection.
  --color {always,auto,never}
                        colorize the output. Default to 'auto' or can be
                        'never' or 'always'.
  • 列出 --color 的所有可选参数
  • 列出 -x 的当前选择文字(放弃)
  • 根据输入列出搜索建议(依赖 #23

个人列出这些用户需求,请审阅。

error when network is unavailable

when network is not connected, if I use ydcv, it will shows:
Traceback (most recent call last): File "/usr/bin/ydcv", line 11, in <module> load_entry_point('ydcv==0.5', 'console_scripts', 'ydcv')() File "/usr/lib/python3.6/site-packages/ydcv.py", line 289, in main lookup_word(word) File "/usr/lib/python3.6/site-packages/ydcv.py", line 233, in lookup_word print_explanation(json.loads(data), options) File "/usr/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/usr/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Although this doesn't really affect the use of ydcv, I still hope it can be fixed, :) Just a reminder like "You network is unavailable now" will be fine.

[feature] Support join multi-lines

--- /home/wzy/Desktop/ydcv.py	2022-07-23 21:36:39.586450097 +0800
+++ /usr/lib/python3.10/site-packages/ydcv.py	2022-07-23 22:51:26.334572339 +0800
@@ -344,6 +344,10 @@
                         action="store",
                         default="~/.ydcv_history.txt",
                         help="History file. Default: ~/.ydcv_history.txt")
+    parser.add_argument('--split',
+                        action="store_true",
+                        default=False,
+                        help="Split multi-lines input")
     parser.add_argument('words',
                         nargs='*',
                         help="words to lookup, or quoted sentences to translate.")
@@ -376,12 +380,16 @@
             readline.add_history(word)
     else:
         if options.selection:
-            last = check_output(["xclip", "-o"], universal_newlines=True)
+            last = check_output(["xsel", "-o"], universal_newlines=True)
+            if not options._options.split:
+                last = last.replace("-\n", "").replace("\n", ' ')
             print("Waiting for selection>")
             while True:
                 try:
                     sleep(0.1)
-                    curr = check_output(["xclip", "-o"], universal_newlines=True)
+                    curr = check_output(["xsel", "-o"], universal_newlines=True)
+                    if not options._options.split:
+                        curr = curr.replace("-\n", "").replace("\n", ' ')
                     if curr != last:
                         last = curr
                         if last.strip():
@@ -393,6 +401,8 @@
             while True:
                 try:
                     words = input('> ')
+                    if not options._options.split:
+                        words = words.replace("-\n", "").replace("\n", ' ')
                     if words.strip():
                         lookup_word(words)
                 except KeyboardInterrupt:

Screenshot from 2022-07-23 22-49-40

❯ ydcv --selection
Waiting for selection>
Some earlier results suggest that incorporating local normalization in linear block transform coding methods can improve coding performance
  Translation:
     * 一些早期的研究结果表明,在线性块变换编码方法中加入局部归一化可以提高编码性能
❯ ydcv --selection --split
Waiting for selection>
Some earlier results suggest
that incorporating local normalization in linear block transform coding methods can improve cod-
ing performance
  Translation:
     * 一些早期的结果表明
在线性分块变换编码方法中加入局部归一化可以提高编码质量
荷兰国际集团(ing)性能

配置文件位置遵循XDG规范

man file-hierarchy

  ~/.config/
       Application configuration and state. When a new user is created, this directory will
       be empty or not exist at all. Applications should fall back to defaults should their
       configuration or state in this directory be missing. If an application finds
       $XDG_CONFIG_HOME set, it should use the directory specified in it instead of this
       directory.

建议用 .config/ydcv/ydcv.conf 或者 .config/ydcv.conf

关于退出

建议在交互式环境下翻译"exit"或“quit”时直接退出程序,个人认为实在没有必要。否则只能Ctrl + Z了,Ctrl + C都不起作用。

port to python3

I've ported this script to python3.

(I also use requests instead of urllib2, cause urllib2 is not available on Debian unstable.)

I opened a new branch 'py3' for this.

I'll send a pull request soon.

[advice] Why not use some library colorama to output color?

This program create a wheel:

class Colorizing(object):
    colors = {
        'none': "",
        'default': "\033[0m",
        'bold': "\033[1m",
        'underline': "\033[4m",
        'blink': "\033[5m",
        'reverse': "\033[7m",
        'concealed': "\033[8m",

        'black': "\033[30m",
        'red': "\033[31m",
        'green': "\033[32m",
        'yellow': "\033[33m",
        'blue': "\033[34m",
        'magenta': "\033[35m",
        'cyan': "\033[36m",
        'white': "\033[37m",

        'on_black': "\033[40m",
        'on_red': "\033[41m",
        'on_green': "\033[42m",
        'on_yellow': "\033[43m",
        'on_blue': "\033[44m",
        'on_magenta': "\033[45m",
        'on_cyan': "\033[46m",
        'on_white': "\033[47m",

        'beep': "\007",
    }

    @classmethod
    def colorize(cls, s, color=None):
        if options.color == 'never':
            return s
        if options.color == 'auto' and not sys.stdout.isatty():
            return s
        if color in cls.colors:
            return "{0}{1}{2}".format(
                cls.colors[color], s, cls.colors['default'])
        else:
            return s

报告一个bug KeyError

$ ydcv 
Traceback (most recent call last):
  File "/usr/bin/ydcv", line 11, in <module>
    load_entry_point('ydcv==0.7', 'console_scripts', 'ydcv')()
  File "/usr/lib/python3.7/site-packages/ydcv.py", line 353, in main
    sec = config["YDCV"]
  File "/usr/lib/python3.7/configparser.py", line 958, in __getitem__
    raise KeyError(key)
KeyError: 'YDCV'

环境:
4.19.34-1-MANJARO
ydcv 0.7-1

License unclear

Could you please specify under which license is the scripts released?

Thanks!

UnicodeEncodeError

➜  ydcv git:(master) ./ydcv.py 
> hi
hiTraceback (most recent call last):
  File "./ydcv.py", line 208, in <module>
    lookup_word(words)
  File "./ydcv.py", line 150, in lookup_word
    print_explanation(json.loads(data), options)
  File "./ydcv.py", line 100, in print_explanation
    print(" [{0}]".format(_c(_b['phonetic'], 'yellow')))
UnicodeEncodeError: 'ascii' codec can't encode character u'\u026a' in position 9: ordinal not in range(128)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.