ALL DAY I DREAM ABOUT SEX
作者:夜麻産
今のところ東方のSSで一番好きな話。
パチュリー×小悪魔
この話に出会えて本当に良かった。
http://easy2life.sakura.ne.jp/yotogi2/index.php/24/1282807443
作者:夜麻産
今のところ東方のSSで一番好きな話。
パチュリー×小悪魔
この話に出会えて本当に良かった。
http://easy2life.sakura.ne.jp/yotogi2/index.php/24/1282807443
ラムダ式で書いた関数をリファクタリングしていっている。下にいくほど文章量が少なくなることが分かる。
/** * Created by devel on 2017/03/28. */ var expect = require('expect.js'); var anArray = [2, 3, 4, 5, 7] var sum1 = (array) =>{ var result = 0 for(var index=0; index<array.length; index++){ result = result + array[index] } return result } console.log(sum1(anArray)) var sum2 = (array) =>{ var result = 0 array.forEach((item)=>{ result = result + item }) return result } console.log(sum2(anArray)) var sum3 = (array) =>{ return array.reduce((x, y)=>{ return x + y }) } console.log(sum3(anArray)) expect( sum3(anArray) ).to.eql( 21 )
一番下は単体テスト。
#!/usr/bin/env python # -*- coding: utf-8 -*- # - A simple stopwatch program. import time def main(): # Display the program's instructions print('Press Enter to begin. Afterwards,' ' press ENTER to click the stopwatch,' 'Press ctrl-c to quit.') input() print('started.') starttime = time.time() lasttime = starttime lapNUM = 1 # Start Tracking the lap times. try: while True: input() laptime = round(time.time() - lasttime, 2) totaltime = round(time.time() - starttime, 2) print(f'Lap {lapNUM}: {totaltime} ({laptime})', end='') lapNUM += 1 lasttime = time.time() except KeyboardInterrupt: # Handle the Ctrl-c exception to keep its error message from displaying print('\nDone.') if __name__ == '__main__': main()
簡単なストップウォッチ。エンターキーを押すとスタートする。
ラップタイムもエンターキーを押す。
Ctrlとcキーを同時に押すとストップして”Done.”が表示される。
本に書いてあるようにはできなかった。
#!/usr/bin/env python # -*- coding: utf-8 -*- # Prints the weather for a location from the command line import json import requests import sys import pprint def main(): # Compute location from command line arguments. if len(sys.argv) < 2: print('Usage: quickWeather.py location') sys.exit() #location = ' '.join(sys.argv[1:]) # Download the Json data from OpenWeatherMap.org's API. url = 'http://weather.livedoor.com/forecast/webservice/json/v1?city=400040' # 久留米 print(url) response = requests.get(url) response.raise_for_status() # Load JSON data into a python variable. weatherData = json.loads(response.text) # Print weather descriptions w = weatherData['forecasts'] location = weatherData['location']['city'] print(f'場所 : {location}') for i in range(3): date = w[i]['dateLabel'] telop = w[i]['telop'] print(f'{date} : {telop}') if __name__ == '__main__': main()
OpenwetherMapをうまく扱えなかったので
Livedoor Weather Web Service / LWWS
で代用した。
・IDを自動で設定し入力。
例えば、 北海道と入力すると、対応するIDを見つけて、urlに代入する。
・tkinterなどを使ってGUIを作り、入力しやすくする。
Pythonで文字列に数値を埋め込む方式は、”%”やstr.format()があった。
Python 3.6では新しくf文字列(formatted string)が追加された。
これは、r’ ‘のように、先頭にfをつけてf’ ‘のように入力する。{}で囲まれた部分でPythonの式を評価し文字列として出力する。
# !/user/bin/env python def main(): str = 'hello' # 出力 -> hello # %方式 print('%s' %(str)) # str.format()方式 print('{}'.format(str)) # f文字列方式 print(f'{str}') if __name__ == '__main__': main()
# !/user/bin/env python def main(): a = 1 b = 'hello' c = 2.000 d = 64 # 変数を{}の中に入れられる。 print(f'{a} {b} {c}') # 1 hello 2 # {]の中で計算できる。 print(f'{1+2}') # 3 # 10文字の範囲で右そろえ print(f'{a:10}') # 1 # 10文字の範囲で左揃え print(f'{a:<10} {b:<10}') #1 hello # 10文字の範囲で中央揃え print(f'{a:^10} {b:^10}') # 1 hello # 小数点表示範囲 print(f'{c:.1f} {c:.2f} {c:.3f}') # 2.0 2.00 2.000 # 8進数、16進数変換して表示 print(f'10進数:{d} 8進数:{d:o} 16進数:{d:x}') # 10進数:64 8進数:100 16進数:40 if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- # -Removes the header from all CSV files in the current working directory. import csv import os def main(): os.makedirs('headerRemoved', exist_ok=True) # Loop through every file in the current working directory for csvfilemane in os.listdir('.'): if not csvfilemane.endswith('.csv'): continue print(f'Removing header from {csvfilemane} ...') # Read the CSV file in (skipping first row). csvRows = [] with open(csvfilemane) as csvFileobj: readerobj = csv.reader(csvFileobj) for row in readerobj: if readerobj.line_num == 1: continue csvRows.append(row) # Write out the CSV file. with open(os.path.join('headerRemoved', csvfilemane), 'w', newline='') as csvFileobj: csvWriter = csv.writer(csvFileobj) for row in csvRows: csvWriter.writerow(row) if __name__ == '__main__': main()
カレントディレクトリの.csvファイルのヘッダーを消すスクリプト。
もともとのファイルは変更されず、headerRemovedのフォルダに変更したファイルが保存される。
global変数のやり方がいまいち良く分かっていない。
main()の外で変数の定義をすればよいのだろうか・・・
#!/usr/bin/env python # -*- coding: utf-8 -*- a = 1 def main(): def y(): global a print(a) b = 1 def x(): global b print(b) y() x() if __name__ == '__main__': main()
Traceback (most recent call last): File "C:/Users/devel.MASTRE/PycharmProjects/Tkinter/test2.py", line 27, in <module> main() File "C:/Users/devel.MASTRE/PycharmProjects/Tkinter/test2.py", line 23, in main 1 x() File "C:/Users/devel.MASTRE/PycharmProjects/Tkinter/test2.py", line 19, in x print(b) NameError: name 'b' is not defined Process finished with exit code 1
この書き方だとaはグローバル関数になっていて、bは定義されていない。
変数はどこで定義すればいいのだろう?
お気楽 Python/Tkinter 入門でtkinterについて勉強中。 http://www.geocities.jp/m_hiroi/light/pytk01.html#chap02 16進数の扱い方で詰まった。 f”の使い方が少し分かった。
#!/usr/bin/env python # -*- coding: utf-8 -*- from tkinter import * def main(): # メインウィンドウ root = Tk() # スケールの値を格納 red = IntVar() red.set(0) blue = IntVar() blue.set(0) green = IntVar() green.set(0) # ボタンの背景色を変更 def change_color(n): color = f'#{red.get():02X}{blue.get():02X}{green.get():02X}' # f'{変数:桁数n進数}' 桁数とn進数はくっつけてよい button.configure(bg=color) # print(f'#{red.get():02X}{blue.get():02X}{green.get():02X}') # ボタン button = Button(root, text='Button', bg='#000') button.pack() # スケール s1 = Scale(root, label='red', orient='h', from_=0, to=255, variable=red, command=change_color) s2 = Scale(root, label='blue', orient='h', from_=0, to=255, variable=blue, command=change_color) s3 = Scale(root, label='green', orient='h', from_=0, to=255, variable=green, command=change_color) # ウィジェットの配置 s1.pack(fill="both") s2.pack(fill="both") s3.pack(fill="both") # メインループ root.mainloop() if __name__ == '__main__': main()
GUIが簡単?に作れるから初心者でも楽しい。 今のところ・・・
C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.3.1\bin
これで、デフォルトでは32bitのexeが実行されるが、この場所にある64bitのexeのショートカットを作ることで、64bitのPycharmをショートカットから実行することができる。
File -> Settings… ->Editor -> Code Style -> File and Code Templates -> Python Script
このコードをコピペすると最後に改行が入らないため、貼り付けた後に改行を入れる。
改行を入れないと、
W292 no newline at end of file # 最後に改行が無いという警告
が出てしまう。
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by ${USER} on ${DATE}. def main(): if __name__ == '__main__': main()
# Created by ${USER} on ${DATE}.
でユーザ名と一番最初の作成日時を書き入れられる。(pycharmで作成した場合のみ)
File -> Settings… -> Editor -> Colors & Fonts -> Font
この場所でエディタのフォントなどを変更できる。
私は、MeiryoKe_Gothicを使っている。(自分でフォントをインストール?する必要あり)
File -> Settings… -> Editor -> Colors & Fonts -> Console Font
この場所でコンソールのフォントなどを変更できる。
私は、文字サイズを20くらいにしている。
“Solarized light”を使っている。
このサイトから対応しているエディタ・IDEのリンクを選択しダウンロードする。
解凍したファイルから.jarを
File -> import setting で読み取る。
そのあとに
File -> Settings… -> Editor -> Color & Font
Schemeで設定を変更する。
ワーキングフォルダで Alt + insert、python Fileを選択。出てきたウィンドウのkind:の部分をunittstに変更。名前を入力してOKを押すとユニットテストのファイルが作成できる。
これを使うとコードの入力が楽になる。
a.ifと入力すると、自動で
if a:
と変換してくれる。
https://www.jetbrains.com/help/pycharm/2016.3/postfix-completion.html
対症療法。自分でもよくわかっていない。
SettingからPython Debuggerを検索。
PyQt comatibleからGevent compatibleに変更する。
# !/user/bin/env python # - Corrects costs in produce sales spreadsheet. import openpyxl def main(): wb = openpyxl.load_workbook('produceSales.xlsx') sheet = wb.get_sheet_by_name('Sheet') # The produce types and their updated prices PRICE_UPDATES = {'Garlic': 3.07, 'Celery': 1.19, 'Lemon': 1.27} # Loop through the row and update prices. for rowNum in range(2, sheet.get_highest_row()): produceName = sheet.cell(row=rowNum, column=1).value # 指定したセルの中身を取り出している if produceName in PRICE_UPDATES: sheet.cell(row=rowNum, column=2).value = PRICE_UPDATES[produceName] wb.save('updatedProduceSales.xlsx') print('Done') if __name__ == '__main__': main()
エクセルでセルの中から変更したい項目を探して、値を変えるスクリプト。