LoginSignup
11
9

More than 5 years have passed since last update.

Emacsで英和辞書や和英辞書をすぐに引けるようにしたい を改良

Last updated at Posted at 2016-05-31

Emacsで英和辞書や和英辞書をすぐに引けるようにしたい を改良

元のコードは、英語かどうかの判定がascii文字だけなので、英文にスペイン語やドイツ語などの地名や人名が入っていると日本語と判定される。(El Niño エルニーニョとか)

翻訳範囲の指定方法を増やした。
C-u でパラグラフ
C-u C-u で単語
C-u C-u C-u でキーボードから単語や文を入力
引数なしでセンテンス
リージョンを指定していればそのリージョン

(autoload 'google-translate-translate "google-translate" "" t)
(defun google-translate-get-string (arg)
  (or (cond ((stringp arg) arg)
        ((= arg 4)          ;C-u
         (thing-at-point 'paragraph))
        ((= arg 16)         ;C-u C-u
         (thing-at-point 'word))
        ((= arg 64)         ;C-u C-u C-u
         (read-string "Google Translate: "))
        ((use-region-p)         ;リージョン指定
         (buffer-substring (region-beginning) (region-end)))
        (t              ;デフォルト
         (thing-at-point 'sentence)))
      ""))

(defun google-translate-enja-or-jaen (arg)
  "regionか現在位置の単語を翻訳する。C-u付きでquery指定も可能"
  (interactive "p")
  (let* ((string (google-translate-get-string arg))
     (japanesep (string-match "\\cj" string)))
    (run-at-time 0.1 nil 'deactivate-mark)
    (google-translate-translate
     (if japanesep "ja" "en")
     (if japanesep "en" "ja")
     string)))

(push '("*Google Translate*" :height 0.5 :stick t) popwin:special-display-config)

(global-set-key (kbd "C-M-t") 'google-translate-enja-or-jaen)

Microsoft Translatorも改良してみた。

参考:
漢字、ひらがな、カナカナにマッチ
Unicodeで「漢字」の正規表現

ごみ:

;; (defconst google-translate-japanese-chars
;;   "[ぁ-んァ-ヶ々〇〻\u3220-\u3244\u3280-\u32B0\u3400-\u9FFF\uF900-\uFAFF\U00020000-\U0002FFFF]"
;;   "これらの文字が含まれているときは日本語とみなす") ;いい加減
;; (japanesep (string-match
;;           ;;(format "\\`[%s]+\\'" google-translate-japanese-chars)
;;           google-translate-japanese-chars
;;           string)))

追記:
たまたまたどり着いたWikipediaのMan or boy testが翻訳できなかった。

Trying to work it through on paper is probably fruitless, but the correct answer is −67, despite the fact that in the original paper Knuth conjectured it to be −121.

"-67"が"-"(HYPHEN-MINUS, #x2d)ではなくて""(MINUS SIGN, #x2212)なので、(string-match "\\cj" string)では日本語と判定してしまう。
wikipediaのソースは以下のようになっている。

Trying to work it through on paper is probably fruitless, but the correct answer is −67, despite the fact that in the original paper Knuth conjectured it to be −121.

やはり、ごみにしたコードのほうが良いかも。
いずれにしても特定の文字の出現だけで言語を判定するのは無理がある。

11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9