Category Archives: python

「python入門」split関数で文字列を分割するサンプルコード

サンプルコード1:
>>> str = ‘http://oosa.cft.sample.com/pdf/prepareinfo.pdf’
>>> print str.split()
[‘http://oosa.cft.sample.com/pdf/prepareinfo.pdf’]
>>> print str.split(‘/’)
[‘http:’, ”, ‘oosa.cft.sample.com’, ‘pdf’, ‘prepareinfo.pdf’]
>>> print str.split(‘/’)[-1]
prepareinfo.pdf
>>> print str.split(‘/’)[-1].split(‘.’)[0]
prepareinfo
>>>

サンプルコード2:
name = str[str.rfind(“/”)+1:str.rfind(“.”)]

Pythonでファイルやディレクトリを削除するサンプルコード

pythonコード:
class Deleter():
def __init__(self, ToPrint=True, Logger=None):
self.Logger = Logger
self.ToPrint = ToPrint
return

def Log(self, Str):
if self.Logger:
self.Logger.Log(Str)
if self.ToPrint:
print Str
return

## フォルダーを削除
# @param FolderName folder to delete
#<br/>
#Example:
#<pre>
# T = Common()
# FolderName = r’Temp’
# T.DeleteFolder(FolderName)
#</pre>
def DeleteFolder(self, FolderName):
””’delete files and folders”’
for Item in os.listdir(FolderName):
TempPath = os.path.join(FolderName, Item)
if os.path.isfile(TempPath):
self.DeleteFile(TempPath)
pass
elif os.path.isdir(TempPath):
self.DeleteFolder(TempPath)
pass
else:
self.Log(“Not a file or folder: %s” % (FolderName))
pass
pass

try:
os.rmdir(FolderName)
self.Log(“Folder deleted: %s” % (FolderName))
except:
self.Log(“Failed to delete folder: %s” % (FolderName))
pass

return

## ファイルを削除
# @param FileName file to delete
#<br/>
#Example:
#<pre>
# T = Common()
# FolderName = r’TempFile.txt’
# T.DeleteFile(FileName)
#</pre>
def DeleteFile(self, FileName):
try:
os.remove(FileName)
self.Log(“File deleted: %s” % (FileName))
except:
self.Log(“Failed to delete file: %s” % (FileName))
pass
return

## フォルダー一覧を削除
# @param FolderList a list of folder to delete
#<br/>
#Example:
#<pre>
# T = Common()
# FolderNameList = [r’Temp1′, r’Temp2′]
# T.DeleteFolders(FolderNameList)
#</pre>
def DeleteFolders(self, FolderNameList):
for FolderName in FolderNameList:
self.DeleteFolder(FolderName)
return

##ファイルリストを削除
# @param FolderList a list of files to delete
#<br/>
#Example:
#<pre>
# T = Common()
# FolderNameList = [r’Temp1.txt’, r’Temp2.txt’]
# T.DeleteFiles(FileNameList)
#</pre>
def DeleteFiles(self, FileNameList):
for FileName in FileNameList:
self.DeleteFile(FileName)
return

Op = Deleter()
Op.DeleteFile(‘pythsample.txt’)
# Failed to delete file: pythsample.txt

python開発–matplotlibで画像を読み取り、表示する

1.画像を表示
import matplotlib.pyplot as plt
import matplotlib.image as mpimg # mpimg
import numpy as np

ctimg = mpimg.imread(‘jiken.png’)
ctimg.shape #(512, 512, 3)

plt.imshow(ctimg)
plt.axis(‘off’)
plt.show()
2.rgb2grayを操作
def rgb2gray(rgb):
return np.dot(rgb[…,:3], [0.299, 0.587, 0.114])

gray = rgb2gray(ctimg)
plt.imshow(gray, cmap=’Greys_r’)
plt.axis(‘off’)
plt.show()

3.画像を圧縮
from scipy import misc
ctimg_new_sz = misc.imresize(ctimg, 0.5)
plt.imshow(ctimg_new_sz)
plt.axis(‘off’)
plt.show()

4.画像を保存
方法1
plt.imshow(ctimg_new_sz)
plt.axis(‘off’)
plt.savefig(‘ctimg_new_sz.png’)

方法2
from scipy import misc
misc.imsave(‘ctimg_new_sz.png’, ctimg_new_sz)

方法3
np.save(‘ctimg_new_sz’, ctimg_new_sz)
img = np.load(‘ctimg_new_sz.npy’)

pythonでmac物理アドレスを取得する

方法1
>>> import uuid
>>> node = uuid.getnode()
>>> mac = uuid.UUID(int=node)
>>> addr = mac.hex[-12:]
>>> addr

方法2
#!/bin/python

import os
import re

def GetMacAddressFun():
if os.name == ‘nt’:
try:
ret = ”
CmdLine = ‘ipconfig /all’
r = os.popen(CmdLine).read()
if r:
L = re.findall(‘Physical Address.*?([0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2})’, r)
if len(L) > 0:
ret = L[0]
except:
pass

elif os.name == “posix”:
try:
ret = ”
CmdLine = ‘ifconfig’
r = os.popen(CmdLine).read()
if r:
L = re.findall(‘HWaddr.*?([0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2})’, r)
if len(L) > 0:
ret = L[0]
except:
pass
else:
pass
return ret

if __name__ == ‘__main__’:
mac = GetMacAddressFun()
print mac
m=raw_input()

Pythonでバイナリファイルを読み書き操作

方法1
opfile=open(‘d:\\t’,’rb’)
s=opfile.read(1)
byte=ord(s)
print hex(byte)

方法2
import struct
opfile=open(‘d:\\t’,’rb’).read(1)
print struct.unpack(‘c’,opfile)
print struct.unpack(‘b’,opfile)

Pythonでランダムな文字列を作成するサンプル

コード下記

import os, math
from base64 import b64encode
randStr = lambda n: b64encode(os.urandom(int(math.ceil(0.75*n))),’-_’)[:n]

for x in xrange(5):
print randStr(10)

Pythonでテキストファイルを読む方法まとめ

1.readline()
file = open(“startnews24python.txt”)
while 1:
line = file.readline()
if not line:
break
pass # do something
file.close()
2.fileinput
import fileinput
for line in fileinput.input(“startnews24python.txt”):
pass

3.readlines()
file = open(“startnews24python.txt”)
while 1:
lines = file.readlines(100000)
if not lines:
break
for line in lines:
pass # do something
file.close()

4.イテレータ
file = open(“startnews24python.txt”)
for line in file:
pass # do something
file.close()

Python入門–Datetime、TimeStamp、UTC、localtimeの相互変換する方法

1.TimeStampをDatetimeに変換する
def timestamp2datetime(timestamp, convert_to_local=False):
”’ Converts UNIX timestamp to a datetime object. ”’
if isinstance(timestamp, (int, long, float)):
dt = datetime.datetime.utcfromtimestamp(timestamp)
if convert_to_local:
dt = dt + datetime.timedelta(hours=8)
return dt
return timestamp

2.DatetimeをTimeStampに変換する
def datetime2timestamp(dt, convert_to_utc=False):
”’ Converts a datetime object to UNIX timestamp in milliseconds. ”’
if isinstance(dt, datetime.datetime):
if convert_to_utc:
dt = dt + datetime.timedelta(hours=-8)
timestamp = total_seconds(dt – EPOCH)
return long(timestamp)
return dt
3.UTC時間のTimeStamp
def timestamp_utc_now():
return datetime2timestamp(datetime.datetime.utcnow())

4.local時間のTimeStamp
def timestamp_now():
return datetime2timestamp(datetime.datetime.now())

5.UTC時間をローカル時間に変換する
# python-dateutilのインストール
# Ubuntu下:sudo apt-get install python-dateutil
#PIP:sudo pip install python-dateutil
from dateutil import tz
from dateutil.tz import tzlocal
from datetime import datetime

# get local time zone name
print datetime.now(tzlocal()).tzname()

# UTC Zone
from_zone = tz.gettz(‘UTC’)
# China Zone
to_zone = tz.gettz(‘CST’)

utc = datetime.utcnow()

# Tell the datetime object that it’s in UTC time zone
utc = utc.replace(tzinfo=from_zone)

# Convert time zone
local = utc.astimezone(to_zone)
print datetime.strftime(local, “%Y-%m-%d %H:%M:%S”)

Python入門–プログラム実行時間を計測する方法

コード下記
import time
def start_sleep():
time.sleep(3)
if __name__ == ‘__main__’:
#The start time
start = time.clock()
#A program which will run for 3 seconds
start_sleep()
#The End time
end = time.clock()
print(“The function run time is : %.03f seconds” %(end-start))
# End

Python入門–日付(datetime)の基本的な使い方

コード下記:

import datetime, calendar

lastFriday = datetime.date.today( )
oneday = datetime.timedelta(days=1)
lastFriday -= oneday
while lastFriday.weekday( ) != calendar.FRIDAY:
lastFriday -= oneday
print lastFriday.strftime(‘%A, %d-%b-%Y’)