LoginSignup
6
6

More than 5 years have passed since last update.

標準入力で読み込んだ単語の意味をMac内蔵辞書で調べ、単語帳を作る。

Posted at

 ターミナルでPyObjCをインストールする(入っていなければ)。

$ pip3 install pyobjc
wordlist.py
l = [] # 単語リストの作成
word = ""
while word != ".":
  word = input() #標準入力で単語を読みこむ。
  l.append(word)
l.remove(".")
l.sort() # アルファベット順にする。

from DictionaryServices import DCSGetTermRangeInString, DCSCopyTextDefinition
def word_def(word): # Mac内蔵辞書を使って意味を調べる
    try:
        word_range = DCSGetTermRangeInString(None, word, 0)
        return DCSCopyTextDefinition(None, word, word_range)
    except IndexError:
        return 'Not Found'

import csv
f = open('wordlist.csv', 'w', encoding='UTF-8', newline='') # data.csvを新規作成(初期化)
csvwriter = csv.writer(f)
csvwriter.writerow(['word', 'definition'])
f.close()

for i in range(len(l)): # 単語帳の作成
    f = open('wordlist.csv', 'a', encoding='UTF-8', newline='')
    csvwriter = csv.writer(f)
    csvwriter.writerow([l[i],word_def(l[i])]) # 1列目は単語名, 2列目は単語の意味
    f.close()

 ターミナルで以下のように実行する。
 標準入力で単語帳へ加えたい単語を1語ずつ入力し、最後に「.」を入力すると単語帳(wordlist.csv)が作成される。以下は入力例。単語数によっては時間がかかる。

$ python3 wordlist.py
apple
バナナ
herbivore
harsh
plentiful
.

 wordlist.csvは以下のようになる。
wordlist.png

余談

 以前、以下の記事を書き、予想以上の反響をいただいた。複数のPDFを扱う際に有用である。しかし、論文を1本ずつ読む場合には、以下の記事で紹介したコードは無駄が多く、使いにくい。そのため、今回の記事のようなコンパクトなコードも考えてみた。

6
6
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
6
6