LoginSignup
7
9

More than 5 years have passed since last update.

Pythonで作る簡易英単語学習プログラム

Last updated at Posted at 2017-12-05

概略

 Pythonを使って、英語の単語学習プログラムを作成した。単語の入力は、コマンドラインで行い、答えの英単語を読み上げてもらえるようにした。
 単語の読み上げのライブラリは、pyttsx3 - Text-to-speech x-platform を用いた。

ソースコード

英単語.py
import random
import collections

import pyttsx3

QA = collections.namedtuple("QA", "q, a")

# 音声読み上げの初期設定
engine = pyttsx3.init() # 初期化
voices = engine.getProperty('voices')
# 用いたOSはwindows10
engine.setProperty('voice', voices[1].id) # 合成音声の選択


lis = [QA(q="An infectious disease [   ]there.", a="broke out"),
       QA(q='Box seats are really hard to [   ].', a='come by')]


def speak(word):
    engine.say(word)
    engine.runAndWait()


def main():

    random.shuffle(lis)

    for i in lis:
        print(i.q)
        ans = input()

        if ans == i.a:
            print("正解")
            print(i.a)
        else:
            print("不正解")
            print(i.a)
        speak(i.a)

    print('#########\nFinish')


if __name__ == '__main__':
    main()

改善点

 このコードだと、単語を読み上げるまで次の問題が表示されない。そのため、並列や平行処理をすると上手くいくのだろうか。
 また、問題をcsvなどで読み込み、pickle などを使ってデータを保存できるようにすると、ソースコードに直接書き込みをしなくて良くなる。

※追記 並列処理

並列処理.py
import random
import collections
import multiprocessing
from multiprocessing import Queue

import pyttsx3

QA = collections.namedtuple("QA", "q, a")

engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)


lis = [QA(q="An infectious disease [   ]there.", a="broke out"),
       QA(q='Box seats are really hard to [   ].', a='come by'),]


class Speak(multiprocessing.Process):
    def __init__(self, q):
        super(Speak, self).__init__()
        self.q = q

    def run(self):
        while True:
            data = self.q.get() #単語を受け取る。
            engine.say(data)
            engine.runAndWait()


def main():

    random.shuffle(lis)

    q = Queue()
    j = Speak(q)
    j.start()

    for i in lis:
        print(i.q)
        ans = input()

        if ans == i.a:
            print("正解")
        else:
            print("不正解")

        print("答え:", i.a)
        q.put(i.a) # 正解の単語を送る

    print('#########\nFinish')
    j.terminate()


if __name__ == '__main__':
    main()

 Queueを使えばうまくやれることが分かった。

参考文献

Pythonの非同期通信(asyncioモジュール)入門を書きました
Python 標準ライブラリ探訪 (23) ~ multiprocessing.Pool 編 ~
pyttsx always busy
python でコマンド実行。サブプロセスの終了待ち・強制終了・親プロセスと一緒に殺す。
multiprocessingのQueue型変数の使い方

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