Python mapit.py with the webbrowser Module

# !/user/bin/env python
# -Launches a map in the browser using an address from the
# command line or clipboard

import webbrowser, sys, pyperclip


def main():
    if len(sys.argv) > 1:
        # Get address from command line
        address = ' '.join(sys.argv[1:])
    else:
        # Get address from clipboard
        address = pyperclip.paste()

    # open website
    webbrowser.open('https://www.google.com/maps/place/' + address)


if __name__ == '__main__':
    main()

コマンドラインに住所を打ち込むか、住所をクリップボードにコピーした状態でスクリプトを実行すると、グーグルマップのサイトがWebブラウザで起動して住所の場所を表示する。

サウスパーク s07e12 All About Mormons

この話で好きなセリフ

ユタから来た転校生、ゲリーの最後のセリフ

Listen, I just wanted to let you know you don’t have worry about me trying to be your friend anymore.

カイル 「I don’t?」

Look, maybe us MORMONS do believe in crazy stories that make absolutely no sense.

And maybe Joseph Smith did make it all up but I have a great life and a great family.

And I have the book of MORMON to thank for that.

The truth is, I don’t care if Joseph Smith made it all up…

Because what the church teaches now  is loving your family, being nice and helping people.

And even though people in this town might think that’s stupid, I still choose to believe in it.

All I ever did was try to be your friend, Stan.

But you’re so high and mighty you couldn’t look past my religion and just be my friend back.

You’ve got a lot of growing up to do, Buddy.

Suck my balls.(タマ、なめやがれ!)

 

最後のセリフが痛快。

論理を重視してゲリーの本当の気持ちを考えず、変な宗教であり間違ってると言い切ったカイル。

たとえモルモン教が本当でなくても、その教えによって幸せな家族と人生があるというゲリー。

 

どちらが正しいというわけではなく、何を選んで、どんな風になりたいか。

大事なことを教えてくれるエピソードだと思う。

 

I don’t care if   #しても構わない

suck #舐める

 

 

 

All About Mormons

http://southpark.cc.com/full-episodes/s07e12-all-about-mormons

Python Backing Up a Folder into a ZIP File

指定したディレクトリをバックアップするスクリプト

# !/user/bin/env python
# - Copeies an entire folder and its contents into
# a Zip file whose filename increments.

import zipfile, os


def backupToZip(folder):
    # Backup the entire contents of ''folder' into a Zip file
    folder = os.path.abspath(folder) # make sure folder is absolute
    # Figure out the filename this code should use based on what files already exist
    number = 1
    while True:
        zipFilename = os.path.basename(folder) + '_' +str(number) + '.zip'
        if not os.path.exists(zipFilename):
            break
        number += 1
    # Create Zip file.
    print('Creating {}'.format(zipFilename))
    backupzip = zipfile.ZipFile(zipFilename, 'w')

    # Walk the enter folder tree and compress the files in each folder.
    for foldername, subfolders, filenames in os.walk(folder):
        print('adding files in {}'.format(foldername))
        # Add the current folder to the Zip file.
        backupzip.write(foldername)
        # Add all the files in this folder to the zip file
        for filename in filenames:
            newBase = os.path.basename(folder) + '_'
            if filename.startswith(newBase) and filename.endswith('.zip'):
                continue
            backupzip.write(os.path.join(foldername, filename))
    backupzip.close()
    print('done')


def main():
    backupToZip("1702")



if __name__ == '__main__':
    main()

 

Python Renaming Files with American-Style Dates to European-Style Dates

アメリカ式の日付表記をヨーロッパ式の日付表記に変えるスクリプト

# !/user/bin/env python
# - Renames filenames with American MM-DD-YYYY date format
# to European DD-MM-YYYY

import shutil, os, re


def main():
    # Create a regex that matches files with American MM-DD-YYYY date format
    datePattern = re.compile(r"""
                    ^(.*?)          # all text before the date
                    ((0|1)?\d)-     # one or two digits for the month
                    ((0|1|2|3)?\d)- # one or two digits for the day
                    ((19|20)\d\d)   # four digits for the year
                    (.*?)$          # all text after the date
                    """, re.VERBOSE)

    # loop over the files in the working directory
    for amerFilename in os.listdir('.'):
        mo = datePattern.search(amerFilename)

        # Skip file without date
        if mo == None:
            continue

        # Get different parts of the file name
        beforePart = mo.group(1)
        monthPart = mo.group(2)
        daypart = mo.group(4)
        yearPart = mo.group(6)
        afterPart = mo.group(8)

        #Form the European-style filename
        euroFilename = beforePart + daypart + '-' + monthPart + '-' + yearPart + afterPart

        #Get the full, absolute file path
        absWorkingDir = os.path.abspath(".")
        amerFilename = os.path.join(absWorkingDir, amerFilename)
        euroFilename = os.path.join(absWorkingDir, euroFilename)

        # Rename the files
        print('Renameing {} to {}'.format(amerFilename, euroFilename))
        shutil.move(amerFilename, euroFilename)





if __name__ == '__main__':
    main()

 

Python import os

import os のメモ

 

# !/user/bin/env python

import os


def main():
    a = os.path.join('use', 'spam', 'bin') # パスをつなげる
    print(a) # use\spam\bin

    b = os.getcwd() # カレントディレクトリを表示
    print(b)

    c = os.chdir('C:usr') # カレントディレクトリの変更

    d = os.listdir(b) # 参照したディレクトリの中身を表示
    print(d)


if __name__ == '__main__':
    main()

 

 

Python Multiclipboard

クリップボードの値をキーワードを設定して保存するスクリプト

 

# !/user/bin/env python
# mcb.pyw - save and loads pieces of text to the clipboard
# Usage: py.exe mcb.pyw save <keyword> - Save clipboard to keyword
#        py.exe mcb.pyw <keyword> - Loads keyword to clipboard
#        py.exe mcb.pyw list - Load all keyword to clipboard

import shelve, pyperclip, sys

def main():
    with shelve.open('mcb') as mcbShelf:

        # Save clipboard content
        if len(sys.argv) == 3 and sys.argv[1].lower() == 'save':
            mcbShelf[sys.argv[2]] = pyperclip.paste()
        elif len(sys.argv) == 2:

            #List keywords and load content
            if sys.argv[1].lower() == 'list':
                pyperclip.copy(str(list(mcbShelf.keys())))
                print(str(list(mcbShelf.keys())))
            elif sys.argv[1] in mcbShelf:

                pyperclip.copy(mcbShelf[sys.argv[1]])

if __name__ == '__main__':
    main()

 

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

を参照!