Python Reading Data from a Spreadsheet

# !/user/bin/env python
# - Tabulates population and number of census tracts for each country

import openpyxl, pprint


def main():
    print('Opening Workbook...')
    wb = openpyxl.load_workbook('censuspopdata.xlsx')
    sheet = wb.get_sheet_by_name('Population by Census Tract')
    countyData = {}

    # Fill in countyData with each country's population and tracts.
    print('Reading rows...')

    for row in range(2, sheet.get_highest_row()+1):
        # Each row in the spreadsheet has data for one census tract.
        state = sheet['B' + str(row)].value
        county = sheet['C' + str(row)].value
        pop = sheet['D' + str(row)].value

        # Make sure the key for this state exist.
        countyData.setdefault(state, {})
        # Make sure the key for this county in this state exists.
        countyData[state].setdefault(county, {'tracts':0, 'pop':0})
        # Each row represents one census tract, so increment exist.
        countyData[state][county]['tracts'] += 1
        # Increase the county pop by the pop in this census tract.
        countyData[state][county]['pop'] += int(pop)
    # open a new text file and write the contents of countyData to it.
    print('Writing results...')
    with open('census2010.py', 'w') as resultFile:
        resultFile.write('allData = ' + pprint.pformat(countyData))

    print('Done')

if __name__ == '__main__':
    main()

スプレッドシートを読み込んで、.pyに辞書型でデータを保存するスクリプト。

 

 

 

Python “I’m Feeling Lucky” Google Search

# !/user/bin/env python
# - opens several Google search results.

import requests, sys, webbrowser, bs4


def main():
    print('Googling...') # display text while downloading the Google page
    res = requests.get('http://google.com/search?q=' + ' '.join(sys.argv[1:]))
    res.raise_for_status()

    # Retrieve top search result links.
    soup = bs4.BeautifulSoup(res.text, 'html.parser')

    # Open a browser tab for each result.
    linkElems = soup.select('.r a')
    numOpen = min(5, len(linkElems))
    for i in range(numOpen):
        webbrowser.open('http://google.com' + linkElems[i].get('href'))


if __name__ == '__main__':
    main()

コマンドラインで実行するときに、

python lucky.py 箱庭

などとして実行するとgoogleで検索した結果の上位5までを新しいタブで開くスクリプト

この場合は、箱庭の検索結果から5つタブが開かれる。

テキストファイルの最後に、青空文庫で使われている「#改ページ」をいれるスクリプト

すごい、ニッチなやつ。

Kindleでweb小説、たとえば東方創想話などを読みたいときwebからダウンロードして、テキストで保存する。

そしてファイルの中身を連結するソフトを使って、一つのテキストファイルにする。

このとき「#改ページ」が入っているとKindle側で章として扱ってくれる。

一つのテキストファイルにまとめないとファイル数が多くなって管理が面倒になる。

そのため、「#改ページ」を自動で入力してくれるスクリプトを書いた。

自分以外に需要がなさそう・・・

改善後

#!/usr/bin/env python
# coding: UTF-8
import os
import os.path


def main():
    list1 = os.listdir()
    list1.sort(key=os.path.getctime, reverse=False)
    print(list1)

    with open('new1.txt', 'w', encoding='utf-8') as f1:

        for filename in list1:
            if filename.endswith('.txt'):
                with open(filename, 'a+', encoding='utf-8') as f:
                   f.write('\n[#改ページ]\n')

                with open(filename, 'r', encoding='utf-8') as f:
                   a = f.read()
                   f1.write(a)

    print('Done')
    A = input('Please Any key')


if __name__ == '__main__':
    main()

 

改善前

import os
import os.path
import sys
import codecs
import pprint

list = os.listdir()
pprint.pprint(list)
list.sort(key=os.path.getctime, reverse=False)
pprint.pprint(list)
file = open("new.txt", 'a', encoding='utf-8')

for i in range(len(list)):
    if list[i] != 'text_conect.py':
        f = open(list[i], 'a', encoding='utf-8')
 
        f.write(u'[#改ページ]\n')
        f.close()

        f = open(list[i], 'r', encoding='utf-8')
        str = f.read()
        file.write(str) 
        f.close()        

file.close()

・直せそうなところ

open(), close() をwith構文を使って書き直す。

for 文のところで in range -> in list にしてわかりやすくする?

 

 

 

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ブラウザで起動して住所の場所を表示する。

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()

 

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