正確に言うと、単語帳の単語をランダムに問題として出力してくれるプログラムをpythonでかいた。
strip()
が便利だった。
説明
./tangocho.org
というファイルを読むことにする。
path = "./tangocho.org"
とする。
中身は
| apple | りんご | | tomato | トマト |
という感じ。
split
指定した語で文字列を分割する。
何も指定しなければ、半角スペースで分割する。
例えば、
s = "| apple | りんご |"
として
s.split("|")
とすると、
['', ' apple ', ' りんご ', '']
と出力される。
リスト内包表記
[ i for i in range(10) if i%2 == 0]
とすると、
[0,2,4,6,8]
となる。
strip
ある文字列の改行とか空白を除去してくれる。
ここまでのまとめ
with open(path) as f: tangos = [ [s.strip() for s in t.split("|") if s.strip()] for t in f.readlines()]
とすると、
[["apple", "りんご"], ["tomato", "トマト"]]
となる。
まとめ
上記のようなリストが作れればあとは、random を使ってランダムに出力できるようにすればいい。
結果的に次のようなものになる。
from random import randint print("org fileを指定してください") path = input() #pathを指定する。例えば、tangocho.orgみたいな with open(path) as f: tangos = [ [s.strip() for s in t.split("|") if s.strip()] for t in f.readlines()] n = len(tangos) # print(tangos) while 1: eigo, nihongo = tangos[randint(0,n-1)] print(eigo, end = " ") if input(): #なにも入力しなければ、そのまま問題が出続ける。何か入力すれば終了する。 print(nihongo) break print(nihongo) print("")