ボックス について

性別:男性 考えていること、思っていることを文章にしていきます。

Python Generating Random Quiz Files

アメリカの州の首都を答えるテストを作るプログラム。

!/user/bin/env python
# - Creates quizzes with questions and answers in
# random order, along with the answer key.

import random


capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':
'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':
'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':
'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':
'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'NewMexico': 'Santa Fe',
'New York': 'Albany', 'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee':
'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont':
'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia',
'WestVirginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}


def main():
    for quizNum in range(35):

        # Create the quiz and answer key files
        quizFile = open('capitalsquiz{}.txt'.format(quizNum + 1), 'w')
        answerkeyFile = open('capitalsquiz_answer{}.txt'.format(quizNum + 1), 'w')

        # Write out the header for the quiz
        quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
        quizFile.write((' ' * 20) + 'State Capitals Quiz (Form {})'.format(quizNum + 1))
        quizFile.write('\n\n')

        # shuffle the order of the states
        states = list(capitals.keys())
        random.shuffle(states)

        # loop through all 50 state, making a question for each
        for questionNum in range(50):
            # Get right and wriong answer
            correctAnswer = capitals[states[questionNum]]
            wrongAnswers = list(capitals.values())
            del wrongAnswers[wrongAnswers.index(correctAnswer)]
            wrongAnswers = random.sample(wrongAnswers, 3)
            answerOptions = wrongAnswers + [correctAnswer]
            random.shuffle(answerOptions)

            # Wwite question and answer options to the quiz file
            quizFile.write('{}. What is the capital of {}\n'.format(questionNum + 1, states[questionNum]))
            for i in range(4):
                quizFile.write(' {}. {}'.format('ABCD'[i], answerOptions[i]))
                quizFile.write('\n')

            # Write the answer key to file
            answerkeyFile.write('{}. {}\n'.format(questionNum + 1, 'ABCD'[answerOptions.index(correctAnswer)]))
        quizFile.close()

if __name__ == '__main__':
    main()

 

関数やクラスを使ったらもっとわかりやすく美しいソースコードになるかも。

Python Phone And Email Address Extractor

# !/user/bin/env python
# - Finds phone numbers and email address on the clipboard
# クリップボードから、電話番号とメールアドレスを見つける。

import re, pyperclip

phoneRegex = re.compile(r'''(
                (\d{3}|\(\d{3}\))?
                (\s|-|\.)?
                (\d{3})
                (\s|-|\.)
                (\d{4})
                (\s*(ext|x|ext.)\s*(\d{2,5}))?
                )''', re.VERBOSE)

# Create email regex
emailRegex = re.compile(r'''(
                    [a-zA-Z0-9._%+-]+
                    @
                    [a-zA-Z0-9.-]+
                    (\.[a-zA-Z]{2,4})
                    )''', re.VERBOSE)



def main():

    #Find matces in clipboard text
    text = str(pyperclip.paste())
    matches = []
    for groups in phoneRegex.findall(text):
        phoneNum = '-'.join([groups[1], groups[3], groups[5]]) # グループの関係がややこしい
        if groups[8] != '':
            phoneNum += ' x' + groups[8]
        matches.append(phoneNum)

    for groups in emailRegex.findall(text):
        matches.append(groups[0])


    # Copy results to clipboard.

    if len(matches) > 1:
        pyperclip.copy('\r\n'.join(matches))
        print('Copied to clipboard:')
        print('\r\n'.join(matches)) # \r\nは、windowsの仕様?
    else:
        print('No phone numbers or email address found.')

if __name__ == '__main__':
    main()

 

 

電話番号の形式とメールの形式の文字列を抜き出す。

例:

https://www.nostarch.com/contactus.htm

をctrl + A でコピーしてスクリプトを実行!

すると

電話番号とメールアドレスがクリップボードにコピーされている。

 

詳しい正規表現については、

http://docs.python.jp/3.6/library/re.html

を参照!

 

Python Star Adder

学習の記録

# !/user/bin/env python
# No Starch Automate the Boring Stuff with Python より
# クリップボードの記録されている文字列の先頭に'★'をつける。

import pyperclip


def main():
    text = pyperclip.paste()

    # 行ごとに文字列を分けて先頭に*をつける。
    lines = text.split('\r\n')  # \r\n 改行コード
    for i in range(len(lines)):
        lines[i] = '★' + lines[i]  # スターを文字列の先頭に追加

    # リストを結合
    text = '\r\n'.join(lines)
    # クリップボードにコピーする。
    pyperclip.copy(text)


if __name__ == '__main__':
    main()

使い方

例えば、

apple
bag
pen

をコピーする。

スクリプトを実行すると、

★apple
★bag
★pen

とクリップボードにコピーされる。

箇条書きのようにすることができる。

Python Password Locker

学んだ記録

# !/user/bin/env python
# No Starch Automate the Boring Stuff with Python より
# pw.py  -  An insecure password locker program
import sys, pyperclip

PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
             'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
             'luggage': '12345',
             }


def main():
    if len(sys.argv) < 2:  # 入力された文字列が二つより少ないなら表示
        print('Usage: Python pw.py [account] - copy account password')
        sys.exit()

    account = sys.argv[1]  # 入力された文字をaccountに保存
    if account in PASSWORDS:
        # 入力された文字列に対応したパスワードを自分のパソコンのクリップボードにコピー
        pyperclip.copy(PASSWORDS[account])
        print('password for ' + account + ' copied to clipborad.')
    else:
        print('There is no account named ' + account)


if __name__ == '__main__':
    main()

例えば、使い方としてコマンドプロンプトで、

$ python pw.py email

と入力。

password for email copied to clipborad

と表示されてクリップボードに、’F7minlBDDuvMJuxESSKHFhTxFtjVB6′

がコピーされる。

これでコピペすることができる。

サウスパーク

英語学習にいいのか・・・

 

皮肉、風刺、悪口が学べます。比較的わかりやすい英語だと思う。全方面に喧嘩を売るスタイルはなかなか見ていて楽しい。公式サイトで無料で視聴できるし、字幕もある。英語がわからないところは、映像を見て想像できる。

 

汚いスラングや英語のジョークも学べる。何より楽しく見れるのが最大の魅力!

 

「なんてこった! ケニーが殺されちゃった!」

「このひとでなし!」

 

公式サイト

http://southpark.cc.com/

大画面での作業

大きい画面でパソコンを使えると、たくさんのスペースを使えるので楽しい。いままでは、最小化したりウィンドウを小さくしていたがサイズを変えることなく作業できるのは快適だ。ノードパソコンからHDMIでつないでいるので、二つの画面で作業できるのも魅力の一つかもしれない。

資料を見ながらの文章を書くこともやりやすいし、動画も脇に置ける。

いままで気づかなかったけど、これはすごい!

お菓子について

お菓子、魔物です・・・

なくてもいいものですがついつい食べてしまう。もし、お菓子がなくなってしまったら人生の潤いが減ってしまうだろう。チョコレート、アイス、ポテトチップスなどなど。魅力的なお菓子はたくさんある。

健康なお菓子に切り替えていくべきだろうか。しかし、モズククッキーやこんにゃくのゼリーだと多少味気がない。一週間に一回、お菓子の日を作って食べてよい日にしよう。普段食べないようにしていれば、たまに食べるお菓子は幸福なものになるだろう。それが出来ないからつらいんだけどねー(笑)

あとは自作かなー。クッキーとかカルメ焼きなど。

あんまり作ったことないなー。たとえできたものが微妙でも自分で作ったものなら文句は入れないはず!

 

お菓子の食べ過ぎで体重が気になる。