困った時のリファレンス辞書

Bookmark this on Google Bookmarks
Pocket

append

list1 = ['a','b','c']
list1.append('d')
print(list1)
#-> ['a','b','c','d']

compile

pattern = re.compile("置換したい文字")
text = pattern.sub("置換後の文字",text)

dump

import pickle
data = 'this is data'
with open('sample.data','wb') as f:
    pickle.dump(data,f)

dict

dictionary = [['a',1],['b',2],['c',3]]
print(dict(dictionary))
-> {'a': 1, 'b': 2, 'c': 3}

enumerate

alphabet = ['a','b','c','d']
for i,word in enumerate(alphabet,1):
    print(i,word,sep=':')
->
1:a
2:b
3:c
4:d

except

text = input('')
try:
    print(int(text))
except:
    print('Not number')

else

x = False
if x: # xがある時 = Trueの時
    pass
else: # 上の条件を満たさない時
    pass

extend

list1 = [0,1,2]
list2 = ['a','b','c']
list1.extend(list2)
print(list1) # -> [0, 1, 2, 'a', 'b', 'c']

float

num = 123
print(float(num)) # -> 123.0

findall

import re
text = 'abc in abcde'
ab_in_abc = re.findall(r'(ab)c',text)
print(ab_in_abc) # -> ['ab', 'ab']

flask

# coding: utf-8
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, Flask!"

if __name__ == "__main__":
    app.run()

html5lib

from bs4 import BeautifulSoup
html = 'xxxxxxxxxx'
soup = BeautifulSoup(html, "html5lib")

html.parser

from bs4 import BeautifulSoup
html = 'xxxxxxxxxx'
soup = BeautifulSoup(html, "html.parser")

input

text = input('テキスト:')
print(text)
-> テキスト:
-> 入力文字

isinstance

sample = ['ab','a','abc']
if isinstance(sample, dict):
    print('This is Dict.')
if isinstance(sample, list):
    print('This is List.')

if

x = 3
if x: # xがある時 = Trueの時
    pass
if not x: # xがない時 = Flaseの時
    pass

index

words = ['a','b','c']
num = words.index('b')
print(num) # -> 1

lambda

sprint = lambda x,l='-':print(l*30,x,l*30,sep='\n')
sprint('Hello')
->
------------------------------
Hello
------------------------------

list

dictionary = {'a': 1, 'b': 2, 'c': 3}
print(list(dictionary))
#-> ['a', 'b', 'c']

lxml

from bs4 import BeautifulSoup
html = 'xxxxxxxxxx'
soup = BeautifulSoup(html, "lxml")

mkdir

import os
os.mkdir('sample')

makedirs

import os
os.makedirs('hoge/huga')

open

with open('smaple.txt','r',encoding='utf-8') as f:
    text = f.read()
with open('smaple.txt','w',encoding='utf-8') as f:
    text = f.write()
with open('smaple.txt','a',encoding='utf-8') as f:
    text = f.write()

requests

import requests
url = 'xxxxxx'
req = requests.get(url,stream=True)
html = req.content

return

def test():
    return 'Hello.'

text = test()
print(text)
-> Hello.

range

for i in range(0,4):
    print(i)
->
0
1
2
3

round

num = round(10/3, 5)
print(num) # -> 3.33333

remove

words = ['a','b','c']
words.remove('a')
print(words) # -> ['b', 'c']

requirements.txt

pip freeze > requirements.txt

set

list_1 = ['a','a','a','b','b','c']
list_2 = list(set(list_1))

print(list_2)
-> ['a','b','c']

sorted

sample1 = ['ab','a','abc']
sample2 = {'b':'2','a':'1','c':'3'}
print(sorted(sample1,key=len,reverse=True))
#-> ['abc', 'ab', 'a']
print(sorted(sample2,key=lambda x:x[0]))
#-> ['a', 'b', 'c']

sub

pattern = re.compile("置換したい文字")
text = pattern.sub("置換後の文字",text)

subprocess

import subprocess
# シェルコマンドでカレントディレクトリにsample.txtを作る例
subprocess.check_output("echo Hello. > sample.txt", shell=True, universal_newlines=True)

try

text = input('')
try:
    print(int(text))
except:
    print('Not number')

tuple

dictionary = [['a',1],['b',2],['c',3]]
print(tuple(dictionary))
#-> (['a', 1], ['b', 2], ['c', 3])

tqdm

from tqdm import tqdm
for i in tqdm(range(10)):
    pass
->
100%|████████████████████████████████████████| 10/10 [00:00<00:00, 43509.38it/s]

webbrowser

import webbrowser
url = 'http://example.com'
webbrowser.open(url)

while

count=1  
while count <= 5:  
    print(count)  
    count+=1  
->
1
2
3
4
5

zip

list1 = ['a','b','c']
list2 = ['1','2','3']
list3 = zip(list1,list2)

zipfile

import zipfile
file_path = 'sample.txt'
with zipfile.ZipFile('sample.zip', 'w', zipfile.ZIP_DEFLATED) as z:
    z.write(file_path)